首页 > 代码库 > JS实现图片不间断滚动

JS实现图片不间断滚动

方法一:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0px;
padding: 0px;
}
#outside{
width: 1200px;
overflow: hidden;
margin: 0 auto;
height: 300px;
}

#outside #inside{
width: 3100px;
}

#outside #inside div{
width: 300px;
height: 300px;
margin: 0px 5px;
background-color: red;
float: left;
}

</style>

</head>

<body>

<div id="outside">
<div id="inside">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
</div>

</body>
</html>

<script type="text/javascript">

var num = 0;

var inside = document.getElementById("inside");
setInterval(function(){
num-=1;
inside.style.marginLeft = num+"px";

console.log(inside.style.marginLeft);

if(num<=-1860){
num = 0;
}
},1);

</script>

方法二:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>

<style type="text/css">
#outside{
width: 800px;
height: 200px;
overflow: hidden;
}
#div{
width: 1000000px;
}
#div1,#div2{
width: auto;
float: left;
}
img{
width: 200px;
height: 200px;
}
</style>


</head>
<body>
<div id="outside">
<div id="div">
<div id="div1">
<img src="http://www.mamicode.com/img/2017-03-14_124354.png" />
<img src="http://www.mamicode.com/img/2017-03-14_124422.png"/>
<img src="http://www.mamicode.com/img/2017-03-14_124708.png"/>
<img src="http://www.mamicode.com/img/2017-03-14_131608.png"/>
</div>
<div id="div2"></div>
</div>
</div>

<script type="text/javascript">

var outside=document.getElementById("outside");
var div1=document.getElementById("div1");
var div2=document.getElementById("div2");

div2.innerHTML=div1.innerHTML;

var gunDong=setInterval(function(){
if(div2.offsetWidth-outside.scrollLeft<=0) {
outside.scrollLeft-=div1.offsetWidth
}else{
outside.scrollLeft++;
}
},10)

//.offsetWidth 是对象的可见宽度,包滚动条等边线,会随窗口的显示大小改变
//.scrollLeft 代表页面利用滚动条滚动到右侧时,隐藏在滚动条左侧的页面的宽度

outside.onmouseover=function() {
clearInterval(gunDong); //鼠标放上滚动停止
}
outside.onmouseout=function() {//鼠标移开继续滚动
gunDong=setInterval(function(){
if(div2.offsetWidth-outside.scrollLeft<=0) {
outside.scrollLeft-=div1.offsetWidth
}else{
outside.scrollLeft++;
}
},10)
}

</script>


</body>
</html>

JS实现图片不间断滚动