css animation

css : 簡單做出「 輸入文字 」動態效果

王曉涵 2021/08/09 12:09:26
4919

我們很常看到網頁 banner 會用「 輸入文字 」的效果來吸引用戶注意,那我們如何簡單做出這個效果呢?

我們只需要用到 css  animation 屬性就可以達到這個效果,讓我們跟著步驟繼續看下去吧!

 

Step 1. 

先把 html 的架構寫出來

<div class="typing-txt-block bg-animation">
    <div class="container">
        <div class="row typing-txt-row">
            <h1 data-text="Typing Animation css">Typing Animation css</h1>
        </div>
    </div>
</div>

 

Step 2.

將 .typing-txt-block 背景圖的圖片以及高度設定好

.typing-txt-block {
  height: 70vh;
  display: block;
  background-image: url("../images/bg-banner-01.jpg");
  background-size: cover;
  background-repeat: no-repeat;
}

接下來設定控制背景圖片 .bg-animation 的動態效果

.typing-txt-block.bg-animation {
  -webkit-animation: bg-animation 20s ease-in-out infinite;
  animation: bg-animation 20s ease-in-out infinite;
}

 bg-animation 的動畫設定:

   -- 背景圖片上下位移

@keyframes bg-animation {
  0% {
    background-position: top;
  }
  50% {
    background-position: bottom;
  }
  100% {
    background-position: top;
  }
}

 

Step 3.

利用 position 的觀念,將文字區塊垂直置中在圖片正中央

.typing-txt-block .container h1 {
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  -ms-transform: translate(-50%, -50%);
  transform: translate(-50%, -50%);
  text-transform: uppercase;
  margin: 0;
  padding: 0;
  letter-spacing: 5px;
  color: transparent;
}

再利用偽元素 ::before ,將要呈現的文字顯示以及輸入文字動態效果的 css 樣式寫入

.typing-txt-block .container h1::before {
  content: attr(data-text);
  position: absolute;
  top: 0px;
  left: 0px;
  width: 100%;
  height: 100%;
  color: #fff;
  overflow: hidden;
  border-right: 1px solid #ffffff;
  animation: type 3s steps(18), blink 0.5s infinite alternate;
  -webkit-animation: type 3s steps(18), blink 0.5s infinite alternate;
  white-space: nowrap;
}

type 的動畫設定:

-- 在 3 秒內將文字寬度以 18 格從 0% ~ 100% 顯示,只播放一次。

@keyframes type {
  0% {
    width: 0%;
  }
  100% {
    width: 100%;
  }
}

blink 的動畫設定:

-- 每 0.5s 顯示輸入的閃爍線,並無限播放閃爍線顏色(從透明變為白色)

@keyframes blink {
  from {
    border-color: transparent;
  }
  to {
    border-color: #ffffff;
  }
}

 

這樣就完成了有質感的動態效果啦!!

 

 

參考來源

https://codepen.io/uiswarup/pen/JBMGbb

https://codepen.io/oleg-kucherenko/pen/BXYLKL

王曉涵