<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.demo{
width:512px;
height:500px;
border:1px solid black;
margin:100px auto;
overflow:hidden;
position:relative;
}
.demo .shang{
width:512px;
height:250px;
position:absolute;
top:0;
left:0;
}
.demo .xia{
width:512px;
height:250px;
position:absolute;
bottom:0;
left:0;
}
#pic{
position:absolute;
}
</style>
<script>
window.οnlοad=function()
{
function $id(id){return document.getElementById(id);}//这个函数必须写在下面一句调用前
var num=0;//写在函数外面,鼠标每次经过num值都不同,每次鼠标一经过top值都会减小50
var timer=null;//设定定时器的名称
//鼠标经过上面的时候
$id("shangpic").οnmοuseοver=function()
{
clearInterval(timer); //习惯:使用定时器之前要清除之前的定时器
//alert("啊啊啊");
//var num=0; 写在函数内,鼠标每次一经过上面盒子,num值都是0,事件执行的效果只会上移一次50px
// num=num-50;
//$id("pic").style.top=num+"px"; //错误写法:$id(pic).top=num;引用$id(id)函数要加引号,style , 以及单位
timer=setInterval(fn,10);
function fn()
{
if(num>= -970) //if-else的判断是为了当图片上移到底部正好触及盒子底部时停止继续上移
{
num=num-3;
$id("pic").style.top=num+"px";
}
else{
clearInterval(timer);
}
}
}
//鼠标经过下面的时候,图片下移
$id("xiapic").οnmοuseοver=function ()
{
clearInterval(timer); //习惯:使用定时器之前要清除之前的定时器
timer=setInterval(fun,10);
function fun()
{
if(num<0)
{
num=num+3;
$id("pic").style.top=num+"px";
}
else
{
clearInterval(timer);
}
}
}
$id("demo").οnmοuseοut=function() //鼠标离开大盒子,定时器清除
{
clearInterval(timer);
}
}
</script>
</head>
<body>
<div class="demo">
<img src="mi.png" alt="" id="pic"/>
<span class="shang" id="shangpic"></span>
<span class="xia" id="xiapic"></span>
</div>
</body>
</html>