1. 程式人生 > >javascript實現圖片無縫滾動左右

javascript實現圖片無縫滾動左右

一個能“動”的網站瀏覽起來看著就美觀大氣。今天我就實現四張圖片的無縫滾動,滑鼠進入滾動停止,點選圖片顯示提示資訊。

javascript實現圖片無縫滾動

工具/原料

  • 電腦一臺

方法/步驟

  1. 設定圖片的樣式:

     img

    {    

    height: 100px;

    width: 100px;      

    }

    設定圖片顯示區域div1:

    #div1 {          

    height: 100px;           

    width: 400px;           

    background-color: red;           

    position: relative;           

    top: 50px;           

    left: 0px;           

    margin: 0 auto;           

    overflow: hidden;           

    /*// width:500px;*/        }

    用ul標籤組織圖片:

     #div1 ul {               

    position: absolute;               

    left: 0px;               

    top: 0px;            }         

    #div1 ul li {           

    height: 100px;           

    width: 100px;           

    list-style: none;           

    float: left;          }

    具體樣式表如下:

    javascript實現圖片無縫滾動

  2. 頁面程式碼設計:

    設計文字域顯示圖片偏移量,<div id="Label1"></div>

    兩個<a>標籤控制左右移動,<a href="javascrip:;" id="l1">左</a> &nbsp;&nbsp;&nbsp;&nbsp;<a href="javascrip:;" id="r1">右</a>

    javascript實現圖片無縫滾動

    javascript實現圖片無縫滾動

  3.  

    準備工作完成,現在就來設計JavaScript:

    建立物件,

    var oDiv = document.getElementById("div1") ;    

    var oUl = oDiv.getElementsByTagName("ul")[0];

     var lb1 = document.getElementById("Label1");

     var oLi = oUl.getElementsByTagName("li");

    定義兩個圖片區域(如果註釋掉下面的程式碼效果圖如下)

    oUl.innerHTML = oUl.innerHTML + oUl.innerHTML;//相當於複製了一次所有圖片

     

    javascript實現圖片無縫滾動

  4.  

    讓ul移動函式:

    function move() {         

    if (oUl.offsetLeft < -oUl.offsetWidth / 2)     

           oUl.style.left = "0px";

     if (oUl.offsetLeft > 0)  

            oUl.style.left = -oUl.offsetWidth / 2 + "px";

          oUl.style.left = oUl.offsetLeft + speed + "px";   

        lb1.innerText = oUl.offsetLeft;     };

     

    javascript實現圖片無縫滾動

  5.  

    滑鼠進入停止滾動,滑鼠移開開始滾動:

     oDiv.onmouseover = function ()

    {             

      clearInterval(time1);         

      };         

      oDiv.onmouseout = function () {         

          time1 = setInterval(move, 30);      

         };

     

    javascript實現圖片無縫滾動

  6.  

    設計移動速度speed=2,設定30毫秒移動一次

    var time1 = setInterval(move, 30);

    所有程式碼如下:

     

    javascript實現圖片無縫滾動

  7. 現在就來看看效果吧,滑鼠進入左邊則圖片左移動,滑鼠進入右則圖片右移動。並且顯示了偏移量

    javascript實現圖片無縫滾動

  8. 不同時間點的圖片,顯示效果。現在動畫效果就完成了哦。有興趣的朋友可以試著做做

    javascript實現圖片無縫滾動

來源:https://jingyan.baidu.com/article/b7001fe1a7e7c60e7382dd71.html