<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
.boxs{
width: 300px;
height: 200px;
overflow: hidden;
}
.boxs ul{
margin: 0;
padding: 0;
}
.boxs ul li{
margin: 0;
padding: 0;
float: left;
display: block;
width: 300px;
height: 200px;
}
.a{
background-color: #f00;
}
.b{
background-color: #ccc;
}
.c{
background-color: #ffff00;
}
.d{
background-color: #5E6BA4;
}
</style>
</head>
<body>
<div class="boxs">
<ul id="test1">
<li class="a">1</li>
<li class="b">2</li>
<li class="c">3</li>
<li class="d">4</li>
</ul>
</div>
</body>
<script>
function moveBox(){
var oUl = document.getElementsByTagName("ul");
var oLi = document.getElementsByTagName("li");
var i=0;
return function(){
if(i<oLi.length){
var w = 300;
w = -(w * i) + "px";
oUl[0].style.marginLeft = w;
console.log(w);
i++;
}else{
i=0;
}
}
}
var ok = moveBox();
setInterval(ok,3000);
</script>
</html>
楼主是想实现代码复用吧。想把这个写成一个可以任意调用的公共函数吧?
有以下这些步骤可以帮到你,
把你的 ul
作为参数传递进来,建议使用 id
,比如:
var moveBox=function(ulid){
....
}
然后通过这个传入的 id
去获取它里面的 li
:
document.getElementById(ulid).childNodes
当然,这只是在 ul
下只有 li
的情况下,如果有其他的你需要过滤一下
然后把你找到的 li
进行操作就行了。这样,你只需要传入一个 ul
的 id
即可实现你要的那种效果。其它页面也可以复用了。
以上