不能无缝切换
没有全部按照老师写的,,写出了就是有一个问题 图片从第一张到最后一张 和最后一张到一张有空白 ,,,仔细检查后发现是判断的原因,left值每次要多运动500px,求大神指点解决的方法!!!
/*html结构*/
/*代码部分*/
//获取属性值
function getStyle(element, attr) {
if(element.currentStyle) {
return element.currentStyle[attr];
} else {
return getComputedStyle(element, false)[attr];
}
}
window.onload = function() {
var container = document.querySelector(".warp");
var oUl = container.querySelector(".list");
var oLi = container.querySelector(".list").getElementsByTagName("li");
var Btn = container.querySelector(".buttons");
var oSpan = Btn.getElementsByTagName("span");
var Prev = container.querySelector(".prev");
var Next = container.querySelector(".next");
var arr=[];
var num = 0;
var onff=false;
var timer;
//初始化
for (var i=0;i<oLi.length;i++) {
arr.push(oLi[i]);
}
//console.log(arr[0].innerHTML);
//设置按钮
for(var i = 0; i < oLi.length; i++) {
Btn.innerHTML += "<span>" + (i + 1) + "</span>";
oSpan[i].setAttribute('index', '' + i + '');
}
var aSpan = oSpan[num];
//设置按钮样式
function showBtn() {
for(var i = 0; i < oSpan.length; i++) {
oSpan[i].className = '';
}
oSpan[num].className = "active";
}
showBtn();
//获取li总宽度
var li_Width = parseInt(getStyle(oLi[0], "width")) * oLi.length;
//给ul设置宽度
oUl.style.width = li_Width + 'px';
//获取一个li的宽度
var one_Li = parseInt(getStyle(oLi[0], "width"));
//运动函数
function animate(offset) {
onff=true;
//新的left值
newLeft = parseInt(getStyle(oUl, "left")) + offset;
var time=300;//位移总时间
var interval=30;//位移间隔时间 ?
var speed=offset/(time/interval);//每次位移量
function go(){
if(speed<0 && parseInt(getStyle(oUl, "left")) > newLeft||speed>0 &&
parseInt(getStyle(oUl, "left"))<newLeft){
oUl.style.left = parseInt(getStyle(oUl, "left"))+speed+'px';
setTimeout(go,interval);
}else{
onff=false;
oUl.style.left = newLeft + 'px';
//判断图片滑到最后一张
if(newLeft < -(li_Width - one_Li)) {
oUl.style.left = 0 + 'px';
};
//判断图片滑到第一张
if(newLeft > 0) {
oUl.style.left = -(li_Width - one_Li) + 'px';
}
}
}
go();
}
function autoPlay(){
timer=setInterval(function(){
Next.onclick();
},2000);
}
autoPlay();
function stop(){
clearInterval(timer);
}
container.onmouseover=stop;
container.onmouseout=autoPlay;
//上一张
Prev.onclick = function() {
if(onff){
return;
}
num--;
if(num == -1) {
num = oSpan.length - 1;
}
showBtn();
animate(600);
}
//下一张
Next.onclick = function() {
if(onff){
return;
}
num++;
if(num > oSpan.length - 1) {
num = 0;
}
showBtn();
animate(-600);
}
//按钮点击事件
for(var i = 0; i < oSpan.length; i++) {
oSpan[i].onclick = function() {
//自定义下标
var myIndex = parseInt(this.getAttribute('index')); //获取按钮的index属性=>下标
/*疑问?*/
var offset = -600 * (myIndex - num);
if(onff){
return;
}
animate(offset);
num = myIndex;
showBtn();
}
}
}