js内容部分:
var box1 = document.querySelector(".box1");
var box2 = document.querySelector(".box2");
box1.onclick = function(){
move(this,100);
}
box2.onclick = function(){
slow(this,100);
}
//匀速
function move(obj,target){
obj.myInter = setInterval(function(){
//第一步获取当前居左边的距离
var offsetLeft = obj.offsetLeft;
var num = 10;//走10px
if(offsetLeft==target){
clearInterval(obj.myInter);//清除定时器
}else{
obj.style.left = offsetLeft + num + "px";
}
},1000)
}
//缓动
function slow(obj,target){
obj.myInter = setInterval(function(){
//第一步获取当前居左边的距离
var offsetLeft = obj.offsetLeft;
var num = (target - offsetLeft)/10;
num>0?num = Math.ceil(num):num=Math.floor(num);
if(offsetLeft==target){
clearInterval(obj.myInter);//清除定时器
}else{
obj.style.left = offsetLeft + num + "px";
}
},500)
}
以上是使轮播图匀速与缓动的js效果,下面提取。在编程的过程中可以提取其中的函数,直接调用即可。
提取部分:
匀速
//匀速
function move(obj,target){
obj.myInter = setInterval(function(){
//第一步获取当前居左边的距离
var offsetLeft = obj.offsetLeft;
var num = 10;//走10px
if(offsetLeft==target){
clearInterval(obj.myInter);//清除定时器
}else{
obj.style.left = offsetLeft + num + "px";
}
},1000)
}
缓动:
//缓动
function slow(obj,target){
obj.myInter = setInterval(function(){
//第一步获取当前居左边的距离
var offsetLeft = obj.offsetLeft;
var num = (target - offsetLeft)/10;
num>0?num = Math.ceil(num):num=Math.floor(num);
if(offsetLeft==target){
clearInterval(obj.myInter);//清除定时器
}else{
obj.style.left = offsetLeft + num + "px";
}
},500)
}