原生JS透明度动画案例
程序员文章站
2024-03-24 08:33:10
...
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>透明度动画</title>
</head>
<style>
*{margin: 0;padding: 0;}
#box{width: 100px;height: 100px;background: red;opacity: 1;}
</style>
<body>
<div id="box"></div>
</body>
<script>
window.onload = () => {
const boxElem = document.getElementById("box");
let obj = {
boxElem,
timer:null
}
boxElem.onmouseover = () => {
velocity.call(obj,100,10);//this对象,开始时的透明度,结束时的透明度
}
boxElem.onmouseout = () => {
velocity.call(obj,30,100);//this对象,开始时的透明度,结束时的透明度
}
}
function velocity(start,end){//开始时的透明度,结束时的透明度
this.timer && clearInterval(this.timer);
let tempOpacity = start;
this.timer = setInterval(() => {
if(tempOpacity === end){
clearInterval(this.timer);
return;
}
tempOpacity = tempOpacity + (start === 100 ? -10 : 10);
this.boxElem.style.opacity = tempOpacity / 100;
}, 30);
}
</script>
</html>