[英]setInterval() does not work on style.marginLeft
I want the box I have created to move 20px every .5 seconds but it happens only once with setInterval()
我希望我创建的框每 0.5 秒移动 20 像素,但它只发生一次
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>
the push function needs to be modified推送功能需要修改
<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>
You need to add 20 extra pixel every iteration每次迭代都需要添加 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.