首页 > 代码库 > 跑马灯小效果

跑马灯小效果

今天在项目中需要一个图片跑马灯的效果 , 就用js写了一个 

直接上代码吧:

css代码:

*{margin:0;padding:0;}    .clearfix:after {    content: "";    display: table;    clear: both;  }    .clearfix: {        *zoom: 1;    }    #div1{        width:1200px;height:200px;margin:100px auto;position:relative;background:red;        overflow:hidden;    }    #div1 ul{        position:absolute;left:0;top:0;    }    #div1 ul li{        float:left;        list-style:none;    }

 

HTML代码:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Document</title></head><body>    <div id="div1">        <ul class="clearfix">            <li><img src="image/1.jpg" alt=""></li>            <li><img src="image/2.jpg" alt=""></li>            <li><img src="image/3.jpg" alt=""></li>            <li><img src="image/4.jpg" alt=""></li>        </ul>    </div></body></html>

 

  js代码:

window.onload = function(){        // 1. offsetLeft:获取物体的左边距         var oDiv = document.getElementById(‘div1‘);        var oUl = oDiv.getElementsByTagName(‘ul‘)[0];        var aLi = oUl.getElementsByTagName(‘li‘);        oUl.innerHTML = oUl.innerHTML+oUl.innerHTML;        oUl.style.width = aLi[0].offsetWidth*aLi.length+‘px‘;        function autoPlay(){             if(oUl.offsetLeft<-oUl.offsetWidth/2){                oUl.style.left = ‘0‘;            }            oUl.style.left = oUl.offsetLeft-2+‘px‘        };        var timer= setInterval(autoPlay,30)        oDiv.onmouseover = function(){            clearInterval(timer);        };        oDiv.onmouseout = function(){            timer = setInterval(autoPlay,30)        }    }

图片直接替换成自己的图片就可以使用

 

跑马灯小效果