鼠标经过的时候,利用offsetLeft获得当前盒子距离左侧的距离,把这个值赋给缓动动画的end值。
当点击的时候记住当前的offsetLeft值,当鼠标经过的时候把之前点击的offsetLeft给现在经过时候的值。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
body{
background-color:#333;
}
ul,ol{
list-style: none;
}
img{
vertical-align: top;
}
#nav{
width: 800px;
height: 42px;
border-radius: 5px;
margin: 100px auto;
background: url("images/rss.jpg") no-repeat right center #FFFFFF;
position: relative;
}
#cloud{
width: 83px;
height: 42px;
background: url("images/1.gif") no-repeat;
position: absolute;
left: 0;
top: 0;
}
#nav ul{
position: absolute;
top: 0;
left: 0;
}
#nav ul li{
float: left;
width: 83px;
height: 42px;
line-height: 42px;
text-align: center;
cursor: pointer;
}
</style>
</head>
<body>
<div id="nav">
<span id="cloud"></span>
<ul>
<li>网站首页</li>
<li>公司介绍</li>
<li>产品介绍</li>
<li>联系我们</li>
<li>公司招聘</li>
<li>官方微信</li>
<li>官方微博</li>
<li>快来看看</li>
</ul>
</div>
</body>
</html>
<script>
function $(id){return document.getElementById(id)}
var lis = $("nav").children[1].children;
var start = 0,end=0;
var current = 0; //存放点击时候的offsetLeft值
for(var i=0;i<lis.length;i++){
lis[i].onmouseover = function () {
end=this.offsetLeft; //鼠标一经过,得到当前盒子的offsetLeft值,给end.
}
lis[i].onmouseout = function () {
end = current;
}
lis[i].onclick = function () {
current = this.offsetLeft;
}
}
setInterval(function () {
start = start + (end-start)/10;
$("cloud").style.left = end+"px";
},10);
</script>