知识点
- background-color: transparent 设置透明
- 凡是由监听事件引起的定时器,一定要遵循先清后设
运行效果
在红线(中线)往上区域,图片往上走
在红线(中线)往下区域,图片往下走
代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{margin: 0;padding: 0;list-style: none;}
body{background-color: #000;}
#box{width: 750px;height: 400px;border: 10px solid red;margin: 100px auto;overflow: hidden;position: relative;}
#pic{position: absolute;left: 0;top: 0;}
#to_top, #to_bottom{width: 100%;height: 50%;position: absolute;left: 0;cursor: pointer;background-color: transparent;}
#to_top{top: 0;}
#to_bottom{bottom: 0;}
</style>
</head>
<body>
<div id="box">
<img id="pic" src="images/timg.jpg" alt="">
<span id="to_top"></span>
<span id="to_bottom"></span>
</div>
<script>
window.onload = function (ev) {
// 1. 获取标签
var box = document.getElementById('box');
var pic = document.getElementById('pic');
var to_top = document.getElementById('to_top');
var to_bottom = document.getElementById('to_bottom');
var intervalId, num = 0;
// 2. 监听鼠标进入事件
// 向上
to_top.onmouseover = function (ev1) {
// 2.1 清除定时器
clearInterval(intervalId);
// 2.2 设置定时器
intervalId = setInterval(function () {
// 步长
num -= 10;
// 判断
if(num > -2466){
pic.style.top = num + 'px';
}else {
clearInterval(intervalId)
}
},20);
};
// 向下
to_bottom.onmouseover = function (ev1) {
// 2.1 清除定时器
clearInterval(intervalId);
// 2.2 设置定时器
intervalId = setInterval(function () {
// 步长
num += 10;
// 判断
if(num <= 0){
pic.style.top = num + 'px';
}else {
clearInterval(intervalId)
}
},20);
};
// 鼠标离开
box.onmouseout = function (ev1) {
// 清除定时器
clearInterval(intervalId)
}
}
</script>
</body>
</html>