首先,搭架子:
* {
margin: 0;
padding: 0;
}
.box {
width: 640px;
height: 300px;
border: 1px solid #000;
margin: 100px auto;
overflow: hidden;
position: relative;
}
.box>.top,
.box>.bottom {
width: 100%;
height: 150px;
position: absolute;
left: 0;
z-index: 999;
}
.box>.bottom {
bottom: 0;
}
.box>img {
position: absolute;
left: 0;
top: 0;
}
<div class="box">
<div class="top"></div>
<div class="bottom"></div>
<img src="images/long.gif" alt="">
</div>
其次,设计逻辑结构:
主要监听鼠标的移入移除事件:
- 在大盒子里再放两个小盒子,并监听这两个小盒子的移入移除事件,当鼠标移入到第一个小盒子也就是上面的小盒子时图片向上滑动,反之向下滑动
- 当鼠标移除盒子时,图片停止滑动
//1.获取需要操作的元素
const oTop = document.querySelector(".top");
const oBottom = document.querySelector(".bottom");
const oImg = document.querySelector("img");
const oDiv = document.querySelector('.box');
let timer = null;
//2.获取图片和盒子的高度,计算最大偏移位
const boxHeight = parseInt(getComputedStyle(oDiv).height);
const imgHeight = parseInt(getComputedStyle(oImg).height);
// console.log(boxHeight);
// console.log(imgHeight);
const maxOffsetY = boxHeight - imgHeight;
// console.log(maxOffsetY);
//2.注册监听事件
oTop.onmouseenter = function() {
move(-10);
};
oBottom.onmouseenter = function() {
move(10);
};
oTop.onmouseleave = close;
oBottom.onmouseleave = close;
//封装移动函数
function move(y) {
let offsetY = parseInt(oImg.style.top) || 0;
timer = setInterval(function() {
offsetY = offsetY + y;
if ((y < 0 && offsetY <= maxOffsetY) ||
(y > 0 && offsetY >= 0)) {
clearInterval(timer);
return;
}
oImg.style.top = offsetY + "px";
}, 10);
}
function close() {
clearInterval(timer);
}