效果圖如下:
主要是通過改變left值和定時器完成此效果
代碼部分如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.box{
width: 500px;
height: 100px;
margin: 10px;
overflow: hidden;
position: relative;
}
.box ul{
height: 100px;
list-style-type: none;
position: absolute;
}
.box li{
float: left;
width: 99px;
height: 100px;
border-right:1px solid white;
background: orange;
color: white;
}
.btn{
float: left;
padding: 7px 10px;
margin: 10px;
cursor: pointer;
}
.btn:hover{
color: white;
background: orange;
}
</style>
<script type="text/javascript">
window.onload=function(){
var content=document.getElementById('content');
var li=content.getElementsByTagName('li');
var btn=document.getElementsByClassName("btn");
var num;
// 無論是向左或向右滾動,滾動一定距離後都會出現空白部分,所以將ul列表中的內容再複製一份,同時需要修改列表的寬度
content.innerHTML=content.innerHTML+content.innerHTML;
content.style.width=li.length*li[0].offsetWidth+"px";
// 定義滾動的函數
function move(){
content.style.left=content.offsetLeft+num+"px";
if(content.offsetLeft>0){ //向右滾動的情況
content.style.left=-(content.offsetWidth/2)+"px";
}else if(content.offsetLeft<-(content.offsetWidth/2)){ //向左滾動的情況
content.style.left="0px";
}
}
setInterval(move,30);
// 通過改變num值的正負改變滾動的方向
btn[0].onclick=function(){
num=-4;
}
btn[1].onclick=function(){
num=4;
}
}
</script>
</head>
<body>
<div class="box" id="box">
<ul id="content">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
<div class="btn">left</div>
<div class="btn">right</div>
</body>
</html>