06js动画匀速操作元素的透明度
2019-03-12 本文已影响0人
An的杂货铺
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 300px;
height: 300px;
background-color:pink;
position: absolute;
left: 200px;
top: 100px;
opacity: 0.3;
}
</style>
</head>
<body>
<div class="box"></div>
<script>
var oDiv = document.querySelector("div");
var timer = null;
var num = 0.3;
oDiv.onmouseover= function() {
startMove(1);// 运动函数
}
oDiv.onmouseout = function() {
startMove(0.3);// 运动函数
}
//创建运动函数
function startMove(target){
clearInterval(timer);
var opacity = oDiv.style.opacity?oDiv.style.opacity:0.3;
var speed = target-opacity>0?0.1:-0.1;
timer = setInterval(function(){
num+=speed;
if(target == oDiv.style.opacity){
clearInterval(timer);
} else{
oDiv.style.opacity = num;
}
},50);
}
</script>
</body>
</html>