js实现图片自动的滚动效果

JavaScript014

js实现图片自动的滚动效果,第1张

自动滚动,主要思路是用js自带的setInterval方法。

定义和用法

setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式。

setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数。

语法

setInterval(code,millisec[,"lang"])

参数

code    必需。要调用的函数或要执行的代码串。  

millisec    必须。周期性执行或调用 code 之间的时间间隔,以毫秒计。  

返回值

一个可以传递给 Window.clearInterval() 从而取消对 code 的周期性执行的值。

简单的例子,仅供参考:

<style>    

*{ margin:0 padding:0 list-style:none}    

#box{ width:840px border:1px solid #000 height:210px margin:30px auto position:relative overflow:hidden}    

#box ul{ position:absolute left:0 top:0}    

#box ul li{ width:200px height:200px float:left padding:5px}    

</style>    

<script>    

window.onload=function(){    

var oBox=document.getElementById('box')    

var oUl=oBox.children[0]    

var aLi=oUl.children    

//复制一份内容    

oUl.innerHTML+=oUl.innerHTML    

oUl.style.width=aLi.length*aLi[0].offsetWidth+'px'    

setInterval(function(){    

var l=oUl.offsetLeft+10    

if(l>=0){    

l=-oUl.offsetWidth/2    

}    

oUl.style.left=l+'px'    

},30)    

}    

</script>    

</head>    

<body>    

<div id="box">    

<ul>    

    <li><img src="img/1.jpg" width="200"></li>    

       <li><img src="img/2.jpg" width="200"></li>    

       <li><img src="img/3.jpg" width="200"></li>    

       <li><img src="img/4.jpg" width="200"></li>    

           

   </ul>    

</div>    

</body>

代码:

    <title></title>

    <style>

        body{

            margin:0

            padding:0

            background-color:transparent

        }

        div{

            width:350px

            overflow:hidden

        }

        table img{

            width:100px

            height:100px

        }

    </style>

</head>

<body>

    <div id="picScroll">

        <table>

            <tr>

                <td><a><img src="../pic/1.jpg" /></a></td>

                <td><a><img src="../pic/2.jpg"></a></td>

                <td><a><img src="../pic/3.jpg"></a></td>

                <td><a><img src="../pic/4.jpg"></a></td>

                <td><a><img src="../pic/5.jpg"></a></td>

            </tr>

        </table>

    </div>

</body>

</html>

<script>

    var target = $('#picScroll')

    var left = 0

    var speed = 30

    function Marqeen() {

        if (target[0].offsetWidth <= left) {

            left -= target[0].offsetWidth

        }

        else {

            left++

        }

        target.scrollLeft(left)

    }

    $(function () {

        var marQueen = window.setInterval(Marqeen, speed)

        target.mouseover(function () {

            clearInterval(marQueen)

        })

        target.mouseout(function () {

            marQueen = window.setInterval(Marqeen, speed)

        })

    })

</script>