先看图,这个是不是很面熟呀!
直接上代码看效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
overflow: hidden;
}
.s {
position: absolute;
top: 376px;
right: 0;
}
.x {
position: absolute;
top: 620px;
right: 0;
}
.box span {
display: block;
width: 20px;
height: 20px;
position: absolute;
bottom: 324px;
right: 10px;
background-color: transparent;
z-index: 10;
}
</style>
</head>
<body>
<div class="box">
<span></span>
<img src="../images/t.jpg" alt="" class="s">
<img src="../images/b.jpg" alt="" class="x">
</div>
<script>
var btn = document.querySelector('span');
var shang = document.querySelector('.s');
var xia = document.querySelector('.x');
btn.addEventListener('click', function() {
animate2(shang, shang.offsetTop + 143, function() {
animate(shang, shang.offsetLeft + 325)
});
animate2(xia, xia.offsetTop + 101, function() {
animate(xia, xia.offsetLeft + 325)
});
})
//往下
function animate2(obj, target, callback) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var step = (target - obj.offsetTop) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetTop == target) {
clearInterval(obj.timer);
if (callback) {
//调用函数
callback();
}
}
obj.style.top = obj.offsetTop + step + 'px';
}, 15)
}
//往右
function animate(obj, target, callback) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var step = (target - obj.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
if (obj.offsetLeft == target) {
clearInterval(obj.timer);
if (callback) {
//调用函数
callback();
}
}
obj.style.left = obj.offsetLeft + step + 'px';
}, 15)
}
</script>
</body>
</html>
效果你一定是见过的