<!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>测试</title>
<style>
body,
div,
span {
margin: 0;
padding: 0;
}
#hide {
width: 200px;
height: 200px;
background-color: aqua;
position: relative;
left: -200px;
}
.out {
display: inline-block;
width: 15px;
background-color: blueviolet;
position: absolute;
right: -15px;
top: 50%;
transform: translateY(-50%);
}
</style>
</head>
<body>
<div id="hide"><span class="out">出来</span></div>
<script>
window.onload = function() {
var hide = document.getElementById("hide");
hide.onmouseover = function() {
startMove(0, 10);
};
hide.onmouseout = function() {
startMove(-200, -10);
};
};
var timer = null;
// function startMoveout() {
// // 防止连续移入元素会生成多个计时器,所以进入之前先清除
// clearInterval(timer);
// var hide = document.getElementById("hide");
// timer = setInterval(function() {
// if (hide.offsetLeft == 0) {
// clearInterval(timer);
// } else {
// hide.style.left = hide.offsetLeft + 1 + 'px';
// }
// }, 17);
// }
// function startMovein() {
// // 防止连续移入元素会生成多个计时器,所以进入之前先清除
// clearInterval(timer);
// var hide = document.getElementById("hide");
// timer = setInterval(function() {
// if (hide.offsetLeft == -200) {
// clearInterval(timer);
// } else {
// hide.style.left = hide.offsetLeft - 1 + 'px';
// }
// }, 17);
// }
// 将上面的代码合并
function startMove(target, speed) {
// 防止连续移入元素会生成多个计时器,所以进入之前先清除
clearInterval(timer);
var hide = document.getElementById("hide");
timer = setInterval(function() {
if (hide.offsetLeft == target) {
clearInterval(timer);
} else {
hide.style.left = hide.offsetLeft + speed + 'px';
}
}, 17);
}
</script>
</body>
</html>