Scrollleft图片自动移动,并根据鼠标的动作,停止或是继续运动
css部分
View Code
1 <style type="text/css">
2 /*设置容器大小
3 -------------------------------------------------------*/
4 #outer
5 {
6 overflow: hidden;
7 width: 300px;
8 border: 1px red solid;
9 height: 148px;
10 padding-top: 0px;
11 position: absolute;
12 left: 30%;
13 top: 30%;
14 }
15 /*设置移动部分的大小,width一定要设置的比外部容器大
16 -------------------------------------------------------- */
17 #part1
18 {
19 height: 148px;
20 width: 600px;
21 overflow: hidden;
22 }
23 /*设置"图片",使它们在一行
24 -------------------------------------------------------- */
25 .samediv
26 {
27 float: left;
28 height: 148px;
29 width: 200px;
30 text-align: center;
31 }
32 #div1
33 {
34 background-color: #FFC0CB;
35 }
36 #div2
37 {
38 background-color: #FFCC00;
39 }
40 #div3
41 {
42 background-color: #009966;
43 }
44 </style>
Html部分
View Code
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5 <title></title>
6 <head>
7 <body>
8 <div id="outer">
9 <div id="part1">
10 <div class="samediv" id="div1">
11 <span>first</span>
12 </div>
13 <div class="samediv" id="div2">
14 <span>second</span>
15 </div>
16 <div class="samediv" id="div3">
17 <span>third</span>
18 </div>
19 </div>
20 </div>
21 </body>
22 </html>
Javascript部分
View Code
<script type="text/javascript" language="javascript">
var step = 2; //步数,单位是px,正值为向右走,负值为向左走
function toright() {
document.getElementById("outer").scrollLeft += step;
/*这里的‘600’是容器与移动部分的width的差值
---------------------------------------------------------*/
if (document.getElementById("outer").scrollLeft == 300) {
step = -2;
} else if (document.getElementById("outer").scrollLeft == 0) {
step = 2;
}
}
var run = setInterval(toright, 100); //设置定时器开始运动
var oDiv = document.getElementById("part1");
/*鼠标放在移动块上就停止运动
-------------------------------------------------------------------*/
oDiv.onmouseover = function () {
clearInterval(run);
}
/*鼠标离开移动块上就继续保持原有运动
-------------------------------------------------------------------*/
oDiv.onmouseout = function () {
run = setInterval(toright, 100);
}
</script>


浙公网安备 33010602011771号