將鼠標懸停在下面的紅色方塊上,查看轉場效果:
CSS 轉場允許您在給定的持續時間內平滑地更改屬性值。
要創建轉場效果,您必須指定兩件事:
<style>
div {
width: 100px;
height: 100px;
background: red;
transition: width 2s;
}
當指定的 CSS 屬性(寬度)更改值時,轉場效果將開始。
現在,當用戶將鼠標懸停在 <div> 元件上時,讓我們為 width 屬性指定一個新值:
div:hover {
width: 500px;
}
</style>
transition-timing-function 屬性可以具有以下值:
div {
transition: width 2s, height 2s, transform 2s;
}
以下示例為轉場添加了變形效果, 請將鼠標懸停在紅色方塊:
div {
transition-property: width;
transition-duration: 2s;
transition-timing-function: linear;
transition-delay: 1s;
}
或使用速記屬性轉換:
div {
transition: width 2s linear 1s;
}
下例實現文本的水平滾動,達到走馬燈的效果:
<style>
div.animate {
animation-name: example;
animation-duration: 12s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
@keyframes example {
from {transform:translatex(-100%);}
to {transform:translatex(100%);}
}
</style>
<div id="animate" style="font-size:3vw">Welcome to CSS animation! Welcome to CSS animation!</div>
下面的示例將“example”動畫綁定到 <div> 元件。 動畫將持續 4 秒,它會逐漸將 <div> 元件的背景顏色從“紅色”更改為“黃色”:
div {
animation-name: example;
animation-duration: 5s;
animation-timing-function: linear;
animation-delay: 2s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
使用速記動畫屬性可以實現與上面相同的動畫效果:
div {
animation: example 5s linear 2s infinite alternate;
}
<!DOCTYPE html> <html> <body> <h1>My First JavaScript Animation</h1> <div id ="container"> <div id ="animate">動畫在此進行</div> </div> </body> </html>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
id = setInterval(frame, 5);
function frame() {
if (/* test for finished */) {
clearInterval(id);
} else {
/* code to change the element style */
}
}
例如:
function myMove() {
let id = null;
const elem = document.getElementById("animate");
let pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}