js控制 @keyframes,实现鼠标移入移出无卡顿效果

JavaScript016

js控制 @keyframes,实现鼠标移入移出无卡顿效果,第1张

var style = document.styleSheets[0]

console.log(style)

document.styleSheets这个接口可以获取网页上引入style样式表。

拿到样式表后就可以操作样式啦~

insertRule方法用来给当前样式表插入新的样式规则。

insertRule(rule,index)

rule:要添加到样式表的规则。

index:要把规则插入或附加到 cssRules 数组中的位置。

js既然可以添加 @keyframes 样式了,那动态传值就方便啦!

附实战笔记一篇

<!DOCTYPE html>

<html>

<style>

div.a {

animation: myfirst 1s

-webkit-animation: myfirst 1s

}

</style>

<style id=dynamic></style>

<body>

<div id='a'>

123

</div>

<script>

var colors = ['red','yellow','blue','green']

window.setTimeout(function (){

var color = colors.shift()

console.log(color)

if (!color) return

var style = document.getElementById("dynamic")

style.innerHTML = '@-webkit-keyframes myfirst{50% {background: '+color+'} }\n'

+ '@keyframes myfirst {50% {background: '+color+'}}'

var a = document.getElementById('a')

a.className = 'a'

window.setTimeout(function(){

a.className = ''

},1000)

window.setTimeout(arguments.callee,1500)

},1000)

</script>

</body>

</html>