
使用jQuery + CSS animation 關鍵影格@keyframes,定義設定動畫漸變,達到按鈕hover後背景從中間展開,擴展到填充整個背景按鈕效果。
開始前先將HTML <button> 先寫好,class為elementor-button ,並再多加入四個同樣的<button>在後面,分別給這四個class加入不同顏色名稱green 、blue、red、orange。
<button class="elementor-button">
Effect Button
</button>
<button class="elementor-button green">
Effect Button
</button>
<button class="elementor-button blue">
Effect Button
</button>
<button class="elementor-button red">
Effect Button
</button>
<button class="elementor-button orange">
Effect Button
</button>jQuery append()一個div區塊
為了達到這個效果,首先使用jQuery append() 方法,在<button> HTML DOM標籤內,動態產生帶有bg-overly命名的class <div>區塊。
$(".elementor-button").append('<div class="bg-overly"></div>');使用jQuery這樣好處在於,能夠動態的產生所需要的元素,並可對整個頁面,甚至整個網站帶有elementor-button class的<button>,append()相同帶有bg-overly命名的class <div>區塊。
開啟瀏覽器檢查元素,可以看到elementor-button class的<button> ,已經產生了,帶有bg-overly命名的class <div>區塊。

Button 樣式
接下來開始寫CSS樣式,因為我們需要讓帶有bg-overly命名的class <div>區塊,在<button>內用position:absolute方式,作為背景方式使用CSS animation動畫,達到我們這次要實作的背景動畫展開的效果。
所以先將 elementor-button class的<button> background-color 為透明,讓我們之後可以看到bg-overly動畫背景區塊,並且position為relative,bg-overly position則為absolute,讓它能對應elementor-button 上一層級<button>這個區塊,z-index 為-1,這樣背景層級順序就會在文字後面,就不會壓到文字了,其他的樣式請參照以的下CSS code。
.bg-overly {
position: absolute;
left: 50%;
top: 0;
width: 0%;
height: 100px;
background-color: #231815;
z-index: -1;
}
.elementor-button {
position: relative;
overflow: hidden;
background-color: transparent;
height: 50px;
width: 300px;
font-size: 20px;
cursor: pointer;
border: 1px solid #000000;
margin: 10px;
}CSS animation @keyframes
動畫使用CSS animation @keyframes方式實現,效果是滑鼠移入:hover後開始動畫動作,如下程式碼。
.elementor-button:hover .bg-overly {
animation-iteration-count: 1;
animation-fill-mode: forwards;
animation-name: onHoverButtonAnimation;
animation-duration:0.2s;
}
@keyframes onHoverButtonAnimation {
0% {
width: 0%;
left: 50%;
}
25% {
width: 25%;
left: 38%;
}
100% {
left: 0%;
width: 100%;
}
}animation-name :動畫名稱
animation-iteration-count:屬性用於指定動畫重複的次數。它可以指定為infinite無限重複動畫。
用法:
animation-iteration-count: number | infinite | initial | inherit;animation-fill-mode:屬性用於指定動畫執行前後所應用的值。
用法:
animation-fill-mode:none | forwards | backwards | both | initial | inherit;@keyframes onHoverButtonAnimation 百分比所代表動畫的關鍵幀,關鍵幀規則可以控制動畫的中間步驟,如下圖,每個關鍵幀所含代的屬性,會依照設定的數值產生漸變動畫。

以上也可透過以下方式簡短的縮寫用法如下:
animation:name duration | timing-function | delay | iteration-count | direction | fill-mode | play-state;範例:
.elementor-button:hover .bg-overly {
animation: onHoverButtonAnimation 0.2s 1 forwards;
}