代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
position: absolute;
left: 0;
top: 0;
}
.box1 {
width: 400px;
height: 400px;
background-color: red;
overflow: hidden;
}
.box2 {
width: 200px;
height: 200px;
background-color: #000;
opacity: 0.5;
top: -200px;
}
.box3 {
width: 200px;
height: 200px;
background-color: #000;
opacity: 0.5;
top: 400px;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2"></div>
<div class="box3"></div>
</div>
</body>
<script>
var box1 = document.querySelector('.box1');
var box2 = document.querySelector('.box2');
var box3 = document.querySelector('.box3');
var dsq_1; //全局变量
var dsq1_1 //全局变量
console.log(box2.offsetTop);
box1.onmouseover = function() {
clearInterval(dsq1_1); //先清除dsq1_1定时器,避免受影响
dsq();
}
box1.onmouseout = function() {
clearInterval(dsq_1);
dsq1();
}
function dsq() {
dsq_1 = setInterval(function() {
//判断当前box2的top值是否大于等于0或当前box3的top值是否小于等于200
// box2最初的top为-200px,box3最初的top为400px
if (box2.offsetTop >= 0 || box3.offsetTop <= 200) {
clearInterval(dsq_1); //清除定时器
} else {
box2.style.top = box2.offsetTop + 1 + 'px'; //阴影从上往下出现
box3.style.top = box3.offsetTop - 1 + 'px'; //阴影从下往上出现
}
}, 1)
}
function dsq1() {
dsq1_1 = setInterval(function() {
if (box2.offsetTop <= -200 || box3.offsetTop >= 400) {
clearInterval(dsq_1);
} else {
box2.style.top = box2.offsetTop - 1 + 'px'; //阴影从下往上消失
box3.style.top = box3.offsetTop + 1 + 'px'; //阴影从上往下消失
}
}, 1)
}
</script>
</html>