区别就是offsetLeft是只读的,而style.left是可以修改的,所以要修改只能修改style.left。
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)
}
这是一个实现轮播图缓动效果的函数,通过offsetleft读取,style.left修改。这个函数不仅能做轮播图,还能做滑动门特效。
分享一下滑动门特效的代码,大家可以尝试一下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="animate.js"></script>
<script>
window.addEventListener('load',function(){
var span = document.querySelector('span')
var li = document.querySelectorAll('li')
console.log(span)
var current = 0;
for(var i = 0 ; i < li.length ; i++){
li[i].addEventListener('mouseenter',function(){
animate(span,this.offsetLeft)
})
li[i].addEventListener('mouseleave',function(){
animate(span,current)
})
li[i].addEventListener('click',function(){
current = this.offsetLeft
})
}
})
</script>
<style>
*{
padding: 0;
margin: 0;
list-style: none;
}
ul{
}
li{
width: 100px;
height: 20px;
text-align: center;
line-height: 20px;
float: left;
}
.span{
display: inline-block;
position: absolute;
width: 100px;
height: 4px;
text-align: center;
/* background-color: blue; */
}
.span1{
display: inline-block;
width: 50px;
background-color: blue;
height: 4px;
}
</style>
</head>
<body>
<div style="overflow: hidden;">
<ul>
<li>123</li>
<li>123</li>
<li>123</li>
<li>123</li>
<li>123</li>
</ul>
</div>
<span class="span">
<span class="span1"></span>
</span>
</body>
</html>
轮播图代码如果有需求,后续再上