日期:2014-05-16  浏览次数:20460 次

JS实现图片滚动的问题
这段代码是滚动图片的,能实现左右和向上滚动,可是我不是很明白为什么第一次循环时(页面加载时)图片会先向左滚动,然后向右滚动,然后再向左滚动,最后才向上滚动,可是后面的循环就只是图片先向左滚动,然后向右滚动,最后向上滚动.还请比较懂JS的朋友指点,先谢了! 我是自学的.代码如下:

<html>  
<head>  
<title> SCROLL </title>  
<style type="text/css">  
#infozone{font-size:12px;color:#aa6;overflow:hidden;width:580px;height:217px;}  
#infozone div{height:217px;line-height:20px;white-space:nowrap;overflow:hidden;}  
</style>  
<script type="text/javascript">  
var tc;  
window.onload=function(){  
  var o=document.getElementById('infozone');
  hscroll(o);  
  window.setInterval(function(){window.clearTimeout(tc);o.firstChild.style.marginLeft='0px';scrollup(o,217,0);},17200);
 }  
function scrollup(o,d,c){  
  if(d==c){  
  var t=o.firstChild.cloneNode(true);  
  o.removeChild(o.firstChild);o.appendChild(t);  
  t.style.marginTop=o.firstChild.style.marginTop='0px';  
  hscroll(o);  
  }  
  else{  
  ch=false;var s=3,c=c+s,l=(c>=d?c-d:0);  
  o.firstChild.style.marginTop=-c+l+'px';  
  window.setTimeout(function(){scrollup(o,d,c-l)},50);  
  }  
}  

function hscroll(o){  
  var w1=o.firstChild.offsetWidth,w2=o.offsetWidth;  
  if(w1<=w2)return;  
  tc=window.setTimeout(function(){hs(o,w1-w2,0,w1-w2)},3500);  
}  

function hs(o,d,c,p){  
  c++;var t=(c>0?-c:c);o.firstChild.style.marginLeft=t+'px';  
  if(c==d){if(d==0){tc=window.setTimeout(function(){hs(o,p,0,p)},2500);}else tc=window.setTimeout(function(){hs(o,0,-p,p)},3500);}  
  else tc=window.setTimeout(function(){hs(o,d,c,p)},5);  
}  
</script>  
</head>  

<body>  
<div id="infozone"><div><img src="image/slide-civil-1.jpg" /></div><div><img src="image/slide-civil-2.jpg" /></div><div><img src="image/slide-env-1.jpg" /></div><div><img src="image/slide-env-2.jpg" /></div></div>
</body>  
</html>

------解决方案--------------------
帮你顶下
------解决方案--------------------
因为第一次加载的时候,W1是小于W2的,那么W1-W2就是负数,既然是负数,在下面的横向滚动函数里
o.firstChild.style.marginLeft=t+'px'; 这句设置图片位置的时候自然是想左滚动的。接下来该函数不断的自我调用(用计时器),注意c++,这里每次调用一次就会自加一次,那么知道c>0的情况,那么t的值就等于-C,这样就变成向又滚动。