<!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>
.xiaomi{
width: 512px;
height: 400px;
border: 1px solid Sred;
margin:100px auto;
overflow: hidden; /*不能省 */
position: relative;
}
.xiaomi span{
position: absolute;
left: 0;
width: 100%;
height: 200px;
}
.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>
function $(id){return document.getElementById(id);}
var num = 0; //控制图片的top值
var timer = null; //定时器名称
$("picUp").onmouseover = function(){
clearInterval(timer);
timer= setInterval(function(){
num-=3;
if(num>=-1070){
console.log(num);
$("pic").style.top=num+"px";
}else{
clearInterval(timer);
}
},30);
}
$("picDown").onmouseover = function(){
clearInterval(timer); //清除之前的时钟
timer=setInterval(function(){
if(num<0){
num++;
$("pic").style.top = num + "px";
}else{
clearInterval(timer);
}
},30);
}
$("picUp").parentNode.onmouseout = function(){
clearInterval(timer);
}
</script>