css動畫沒法實時控制,比如點擊某個元素的時候才觸發(fā)踊东,所以這種場景必須要使用js方法
原生js里面并沒有提供動畫方法北滥,如果要實現(xiàn),必須結(jié)合定時器闸翅,定時改變原生的css樣式,或者定義好一個顯示動畫的class再芋,使用js動態(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>
元素會在設(shè)置class的時候執(zhí)行一次動畫
- jQuery提供animate方法來設(shè)置和執(zhí)行動畫坚冀,比如點擊按鈕使某元素逐漸變高
$("button").click(function(){
$("#box").animate({height:"300px"});
});
- 完整語法:
(selector).animate({styles},speed,easing,callback)
styles就是需要控制的css樣式济赎,可以是以下值:
可以應(yī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联喘,會有一個默認速度,單位毫秒
easing 規(guī)定在動畫的不同點中元素的速度华蜒。默認值是 "swing"辙纬。
可能的值:
"swing" - 在開頭/結(jié)尾移動慢,在中間移動快
"linear" - 勻速移動callback animate 函數(shù)執(zhí)行完之后叭喜,要執(zhí)行的函數(shù)贺拣。