0

我正在尝试通过调整 CSS left 属性和 Javascript 中的 setInterval 函数来在 javascript 中创建滑块效果。我的代码看起来像这样

<body onload="move('imagetag');">
    <div id="container">
        <img id="imagetag" src="img.jpg" style="left:40px; position:absolute;">
    </div>
    <script>
        function move(tag) {
            var target = document.getElementById(tag).style;
            var current = target.left;

            function moveObject() {
                current = parseInt(current) + 10 + 'px';
                console.log(current);
                setTimeout(moveObject, 1000);
            }
            setTimeout(moveObject, 1000);
        }
    </script>
</body>

console.log 打印出正确的值,但它没有反映在 CSS 中。

4

1 回答 1

2

这是因为您不编写样式,您只需阅读它并编辑值本身而不是 target.left

            function move(tag) {    
                var target = document.getElementById(tag).style;
                var current = target.left;                  
                function moveObject () {
                    current = parseInt(current) + 10 + 'px';
                    console.log(current);
                    target.left = current;  // <- 
                    setTimeout( moveObject,1000);
                }
                setTimeout( moveObject, 1000);
            }
于 2013-08-30T07:57:47.373 回答