Maison  >  Article  >  interface Web  >  无缝滚动改进版支持上下左右滚动(封装成函数)_javascript技巧

无缝滚动改进版支持上下左右滚动(封装成函数)_javascript技巧

WBOY
WBOYoriginal
2016-05-16 17:47:181057parcourir

复制代码 代码如下:




   
    无缝滚动——上下
   


   

       
       
       

           

                   
  • 111

  •                
  • 222

  •                
  • 333

  •                
  • 444

  •            

       

   




           

scroll.js:

复制代码 代码如下:

/**********
    功能:实现水平或垂直无缝滚动
    参数:direction方向,总共4个值:left,right,top,bottom
          speed移动距离
          iTime多少时间后开始移动,若不写则页面加载完开始移动
**********/
function scroll(direction,speed,iTime){
    var oDiv = document.getElementById('scroll');
    var oUl = oDiv.getElementsByTagName('ul')[0];
    var aLi = oDiv.getElementsByTagName('li');
    var aBtn = oDiv.getElementsByTagName('a');
    var timer = null;
    var iSpeed = 0;
    var flag = true;    //判断水平移动还是垂直移动

    oUl.innerHTML += oUl.innerHTML;

    switch(direction){
        case 'left':
            iSpeed = -speed;
            oUl.style.width = aLi[0].offsetWidth * aLi.length + 'px';
            flag = true;
            break;
        case 'right':
            iSpeed = speed;
            oUl.style.width = aLi[0].offsetWidth * aLi.length + 'px';
            flag = true;
            break;
        case 'top':
            iSpeed = -speed;
            flag = false;
            break;
        case 'bottom':
            iSpeed = speed;
            flag = false;
            break;
    };

    setTimeout(move,iTime);

    //左按钮和上按钮
    aBtn[0].onclick = function(){
        clearInterval(timer);
        iSpeed = -speed;
        move();
    };

    //右按钮和下按钮
    aBtn[1].onclick = function(){
        clearInterval(timer);
        iSpeed = speed;
        move();
    };

    oUl.onmouseover = function(){
        clearInterval(timer);
    };

    oUl.onmouseout = function(){
        move();
    };

    function move(){   
        timer = setInterval(function(){
            if(flag){
                oUl.style.left = oUl.offsetLeft + iSpeed + 'px';
                if(oUl.offsetLeft                     oUl.style.left = '0';
                }else if(oUl.offsetLeft > 0){
                    oUl.style.left = - oUl.offsetWidth / 2 + 'px';
                }
            }else{
                oUl.style.top = oUl.offsetTop + iSpeed + 'px';
                if(oUl.offsetTop                     oUl.style.top = '0';
                }else if(oUl.offsetTop >= 0){
                    oUl.style.top = - oUl.offsetHeight / 2 + 'px';
                };
            };
        },30);
    };
};

需要注意的是:html 结构必须要像上面的结构一样。

 

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn