setInterval() 不适用于 style.marginLeft
setInterval() does not work on style.marginLeft
我希望我创建的框每 .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>
推送功能需要修改
<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>
每次迭代需要额外添加 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>
我希望我创建的框每 .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>
推送功能需要修改
<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>
每次迭代需要额外添加 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>