setInterval() does not work on style.marginLeft

setInterval() does not work on style.marginLeft

本文关键字:on style marginLeft work not does setInterval      更新时间:2023-09-26

我希望我创建的盒子每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>

每次迭代都需要添加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>

推送功能需要修改

        <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>