我正在尝试通过调整 CSS left 属性和 Javascript 中的 setInterval 函数在 javascript 中创建 slider 效果。 我的代码看起来像这样
<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 打印出正确的值,但它没有反射(reflect)在 CSS 中。
最佳答案
这是因为您没有编写样式,您只是读取它并编辑值本身而不是 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);
}
关于javascript - 设置左样式 CSS 属性以在 Javascript 中移动 slider ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18527730/