1.实现效果
鼠标经过,筋斗云跟随,鼠标离开,筋斗云回到原来的位置。鼠标点击,筋斗云停在该位置。
2.实现思路:
鼠标点击时,更改当前的current即可。同时更新记忆变量current,上面图片中的鼠标离开某个小li,就把目标值设为current。
(注意:鼠标点击时,不需要再移动,直接更新current即可。点击完后,离开鼠标时会再执行鼠标离开事件(即移动到current位置,筋斗云会停留在当前位置),即可达到想要的效果。)
3.代码:
<!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>筋斗云案例</title>
<style>
* {
margin: 0;
padding: 0;
}
.banner {
height: 40px;
padding: 0px;
margin: 0px;
}
ul {
height: 40px;
padding: 0;
margin: 0;
width: 700px;
}
ul>li {
list-style: none;
display: inline-block;
height: 40px;
width: 80px;
line-height: 40px;
text-align: center;
margin: 0;
padding: 0;
cursor: pointer;
}
img {
width: 80px;
height: 40px;
}
.cloud {
position: absolute;
left: 0;
top: 0;
z-index: -1;
}
</style>
<script src="animate.js"></script>
</head>
<body>
<div class="banner">
<span class="cloud"><img src="cloud.gif" alt=""></span>
<ul>
<li>首页新闻</li>
<li>招聘信息</li>
<li>公司简介</li>
<li>上海校区</li>
<li>广州校区</li>
<li>活动策划</li>
<li>师资力量</li>
</ul>
</div>
<script>
var lis = document.querySelector('ul').children;
var cloud = document.querySelector('.cloud')
var init_left = lis[0].offsetLeft;
var current = 0;
for(var i = 0; i < lis.length; i++) {
lis[i].addEventListener('mouseover', function() {
animate(cloud, this.offsetLeft);
});
lis[i].addEventListener('mouseout', function() {
animate(cloud, current);
});
lis[i].addEventListener('click',function(){
current = cloud.offsetLeft;
});
}
</script>
</body>
</html>
缓动画js:
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();
// }
callback && callback();
}
obj.style.left = obj.offsetLeft + step + 'px';
},15)
}