我希望我创建的框每0.5秒移动20px,但只发生一次setInterval()
<style type="text/css">
#box{
background-color: green;
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
setInterval(function(){
push();
},500);
function push(){
var box = document.getElementById('box');
box.style.marginLeft="20px";
}
</script>
答案 0 :(得分:1)
需要修改推送功能
<script type="text/javascript">
setInterval(function(){
push();
},500);
function push(){
var box = document.getElementById('box'),
margin=parseFloat(box.style.marginLeft);
box.style.marginLeft=(margin+20)+"px";
}
</script>
答案 1 :(得分:1)
每次迭代需要添加20个额外像素
setInterval(function(){
push();
},500);
function push(){
var box = document.getElementById('box');
box.style.marginLeft= parseInt(box.style.marginLeft||0) + 20 + "px";
}
#box{
background-color: green;
width: 200px;
height: 200px;
}
<div id="box"></div>