原理一(scrollDiv滚动,浮动改变left值)
大的div(bigDiv)包含一个滚动的div(scrollDiv),这个scroll宽度必须大于bigDiv。当scroll滚动完之后不能显示空白,所以要创建一个同样的scroll放到原来的scroll后面,并把原来的scroll的left值变为0;实现无缝滚动;
原理二(bigDiv滚动其scrollLeft++,使其滚动)
让在外面的bigDiv 滚动ScrollLeft++当到达某个位置是让他复位,然后在++
原理一代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.screen {
width: 600px;
height: 215px;
margin: 100px auto;
background-color: pink;
position: relative;
overflow: auto;
}
img {
/*去掉图片底部三像素问题*/
vertical-align: top;
}
* {
margin: 0;
padding:0;
border: 0;
}
ul {
list-style: none;
}
.screen ul li {
float: left;
}
.screen ul {
width:500%;
position: absolute;
left:0;
top:0;
}
</style>
</head>
<body>
<div class="screen">
<ul id="scroll">
<li><img src="images/01.jpg" alt=""></li>
<li><img src="images/02.jpg" alt=""></li>
<li><img src="images/03.jpg" alt=""></li>
<li><img src="images/04.jpg" alt=""></li>
</ul>
</div>
<script>
var ul = document.getElementById("scroll");
var screen = document.getElementsByClassName("screen")[0];
for(var i = 0; i <= 3; i++){
var li = document.createElement("li");
var child = ul.children[i];
li.innerHTML = child.innerHTML;
ul.appendChild(li);
}
var timer = null;
timer = setInterval(autoScroll,1);
var num = 0;
function autoScroll() {
num -= 0.25;
num <= -1200 ? num = 0 : num;
ul.style.left = num + "px";
}
screen.onmouseover = function () {
clearInterval(timer);
}
screen.onmouseout = function () {
timer = setInterval(autoScroll,1);
}
</script>
</body>
</html>
原理二代码
<html>
<head>
<meta charset="UTF-8">
<title>无缝滚动</title>
</head>
<body>
<div id="demo">
<div id="indemo">
<div id="demo1">
<a href="#">图片一</a>
<a href="#">图片二</a>
<a href="#">图片三</a>
<a href="#">图片四</a>
<a href="#">图片五</a>
<a href="#">图片六</a>
</div>
<div id="demo2"></div>
</div>
<style>
#demo{
background:#FFF;
overflow:auto;
border:1px dashed #CCC;
width:500px;
}
#indemo{
float:left;
width:2000px;
}
#indemo a{
width:100px;
height:100px;
float:left;
background-color:blue;
margin-left:5px;
text-align:center;
line-height:100px;
color:red;
text-decoration:none;
}
#demo1{float:left;}
#demo2{float:left;}
</style>
<script>
var speed=10;
var tab=document.getElementById("demo");
var tab1=document.getElementById("demo1");
var tab2=document.getElementById("demo2");
tab2.innerHTML=tab1.innerHTML;
console.log(tab1.offsetWidth);
console.log(tab2.offsetWidth);
tab.scrollLeft = 100;
console.log(tab.scrollLeft);
function Marquee(){
if(tab2.offsetWidth-tab.scrollLeft<=0){
tab.scrollLeft-=tab1.offsetWidth
} else {
tab.scrollLeft++;
}
}
var MyMar=setInterval(Marquee,speed);
tab.onmouseover=function() {clearInterval(MyMar)};
tab.onmouseout=function() {MyMar=setInterval(Marquee,speed)};
</script>
</div>
</body>
</html>