script type="text/javascript">
		window.onload = function(){
			var container = document.getElementById('container');
			var list = document.getElementById('list');
			var buttons = document.getElementById('buttons').getElementsByTagName('span');
			var prev = document.getElementById('prev');
			var next = document.getElementById('next');
			var index = 1;
			var timer;
			var animated = false;

			function animate(offset){
				animated = true;
				var time = 300;
				var interval = 10;
				var speed = offset/(time/interval);
				var newLeft = parseInt(list.style.left)+offset;

				function go(){
					if((speed < 0 && parseInt(list.style.left) > newLeft) || (speed > 0 && parseInt(list.style.left) < newLeft)){
						list.style.left = parseInt(list.style.left) + speed + "px";
						setTimeout(go,interval);
					}	
					else{
						animated = false;
						list.style.left = newLeft + 'px';
						if (newLeft >-600){
							list.style.left = -3000 + 'px';
						}
						if (newLeft <-3000){
							list.style.left = -600 + 'px';
						}
					}	
				}
				go();
			}

			function play(){
				timer = setInterval(function(){
					next.onclick();
				},2000);
			}

			function stop(){
				clearInterval(timer);
			}

			function buttonsShow(){
				for(var i=0; i<buttons.length; i++){
					if (buttons[i].className == "on"){
						buttons[i].className = "";
					}
				}
				buttons[index-1].className = "on";
			}

			prev.onclick = function(){
				index -=1;
				if (index < 1){
					index = 5;
				}
				buttonsShow();
				if(!animated){
					animate(600);
				}
			}
				

			next.onclick = function(){
				index +=1;
				if(index > 5){
					index =1;
				}
				
				buttonsShow();
				if(!animated){
					animate(-600);
				}
			}

			for(var i=0; i<buttons.length; i++){
				buttons[i].onclick = function(){
					if(this.className == "on"){
						return;
					}
					var clickIndex = parseInt(this.getAttribute('index'));
					var offset = 600*(clickIndex - index);
					animate(offset);
					index = clickIndex;
					buttonsShow();
				}
			}
			container.onmouseover = stop;
			container.onmouseout = play;
			play();

			
		}
	</script>

  

 

 

 

  之前写了一个轮播图,做完发现当我去浏览别的页面再返回时,轮播图会一直自动轮播,轮播的时间是我离开的时间,比如我离开了20s,内置2秒轮播一次,它就会快读轮播10次。而且我在他轮播时如果快速点击2次下一张图,他可能就会出现卡图的现象,就是两张图片各占了轮播图界面的一半。

  针对这个问题,优化步骤是在全局变量中声明一个变量。我用的是animated=false。在animate函数中设置animated=true。如果当轮播图到达最后的位置时,设置animated为false。并且在在切换图片时,在animate(600)和animate(-600)前加一句if(!animated)。

  解释:首先设置一个animated变量,当轮播图达到最后位置时,animated为false。所以当我快速点击2次下一张的时候,由于轮播图还没达到最后位置,所以animated为true。所以就算点击下一张,由于在animate(-600)前加一句if(!animated),if(!animated)为false,所以并不会执行。

    而且当我去浏览别的页面时,由于我在它内置时间2s前离开,animated始终为true,它会数到2s,但是不会轮播,但是当你返回轮播图页面的时候,会迅速直接轮播下一张图片,但是这样的话就不会差很多。

 

 

PS:上面是相关js代码。

 posted on 2016-12-11 14:49  Yhspehy  阅读(1356)  评论(0编辑  收藏  举报