setInterval(function, delay);
设置定时器,无限执行,间隔为delay
clearInterval(id);
关闭定时器,参数为之前setInterval的返回值
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>固定侧边栏</title>
<style>
*{
padding: 0;
margin: 0;
}
#container{
width: 150px;
cursor: pointer;
height: 200px;
margin-top: 200px;
position: relative;
left: -120px;
}
#left{
float: left;
width: 120px;
height: 200px;
background: #C2FFDB;
}
#right{
display: inline-block;
padding: 10px 0;
width: 30px;
height: 60px;
background: #061A5D;
color: white;
text-align: center;
position: relative;
top: 60px;
}
</style>
<script>
window.onload = function(){
alert(document.getElementById("right").offsetParent);
var timer = null;
var target = document.getElementsByTagName("div")[0];
target.onmouseover = function(){
move(0);
}
target.onmouseout = function(){
move(-120);
}
function move(position){
clearInterval(timer);
timer = setInterval(function(){
var speed;
if(position == 0){
speed = 10; // show
}else{
speed = -10; // hide
}
if(target.offsetLeft == position){
clearInterval(timer);
}else{
target.style.left = target.offsetLeft + speed + "px";
}
}, 30);
}
}
</script>
</head>
<body>
<div id="container">
<div id="left">
</div>
<span id="right">看<br/>一<br/>看</span>
</div>
</body>
</html>