<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
.xiaomi{
width: 512px;
height: 400px;
border: 1px solid #f00;
margin: 100px auto;
overflow: hidden;
position: relative;
}
.xiaomi span{
display: block;
position: absolute;
left: 0;
width: 100%;
height: 100px;
background-color: rgba(0,0,0,.2);
cursor: pointer;
}
.up{
top: 0;
}
.down{
bottom: 0;
}
#pic{
position: absolute;
top: 0;
left: 0;
}
</style>
</head>
<body>
<div class="xiaomi">
<img src="mi.png" alt="图片有问题" id="pic" />
<span class="up" id="picUp"></span>
<span class="down" id="picDown"></span>
</div>
</body>
</html>
<script>
//对应的id函数
function $(id){
return document.getElementById(id);
}
var num = 0 ; //控制图片的top值
var timer = null ;//定时器的名称
//在当前的额picUp的id选择器的范围内
$("picUp").onmouseover = function(){
clearInterval(timer);
timer = setInterval(function(){
num -= 3;
num >= -1070 ? $("pic").style.top = num + "px" : clearInterval(timer);
},30)
}
//在当前的额picDown的id选择器的范围内
$("picDown").onmouseover = function(){
clearInterval(timer); //排它思想
timer = setInterval(function(){
num +=3;
num < 0 ? $("pic").style.top = num + "px" : clearInterval(timer);
},30)
}
//没有遮罩层的父节点让它停止定时器
$("picUp").parentNode.onmouseout = function(){
clearInterval(timer);
}
</script>