css動(dòng)畫沒法實(shí)時(shí)控制,比如點(diǎn)擊某個(gè)元素的時(shí)候才觸發(fā),所以這種場(chǎng)景必須要使用js方法
原生js里面并沒有提供動(dòng)畫方法,如果要實(shí)現(xiàn),必須結(jié)合定時(shí)器,定時(shí)改變?cè)腸ss樣式,或者定義好一個(gè)顯示動(dòng)畫的class,使用js動(dòng)態(tài)給元素添加class,比如:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>test</title>
<style>
@keyframes my-animation {
0% {
color: red;
}
50% {
color: green;
}
100% {
color: blue;
}
}
.animtest {
animation: my-animation 3s linear;
}
</style>
<script>
function bgAnim() {
document.getElementById("myanim").classList.add("animtest")
}
</script>
</head>
<body>
<div>
<button onclick="bgAnim()">test</button>
<p id="myanim">animation test</p>
</div>
</body>
</html>
元素會(huì)在設(shè)置class的時(shí)候執(zhí)行一次動(dòng)畫
- jQuery提供animate方法來設(shè)置和執(zhí)行動(dòng)畫,比如點(diǎn)擊按鈕使某元素逐漸變高
$("button").click(function(){
$("#box").animate({height:"300px"});
});
- 完整語(yǔ)法:
(selector).animate({styles},speed,easing,callback)
styles就是需要控制的css樣式,可以是以下值:
可以應(yīng)用動(dòng)畫的屬性:
backgroundPositionX
backgroundPositionY
borderWidth
borderBottomWidth
borderLeftWidth
borderRightWidth
borderTopWidth
borderSpacing
margin
marginBottom
marginLeft
marginRight
marginTop
outlineWidth
padding
paddingBottom
paddingLeft
paddingRight
paddingTop
height
width
maxHeight
maxWidth
minHeight
minWidth
fontSize
bottom
left
right
top
letterSpacing
wordSpacing
lineHeight
textIndent
styles是必需的參數(shù),其他可選,比如速度speed,會(huì)有一個(gè)默認(rèn)速度,單位毫秒
easing 規(guī)定在動(dòng)畫的不同點(diǎn)中元素的速度。默認(rèn)值是 "swing"。
可能的值:
"swing" - 在開頭/結(jié)尾移動(dòng)慢,在中間移動(dòng)快
"linear" - 勻速移動(dòng)callback animate 函數(shù)執(zhí)行完之后,要執(zhí)行的函數(shù)。