gpt4 book ai didi

javascript - 尝试使 the_image.style.left = x_position;但日志显示结果不相等

转载 作者:行者123 更新时间:2023-12-03 07:27:12 24 4
gpt4 key购买 nike

这是一个简单的程序,我想测试 setTimeout 函数,但不起作用。我无法理解当我打印出“the_image.style.left”时它总是显示0,但x_position每次循环都会增加1。我检查了很多次,却找不到原因?你能说出什么问题吗?非常感谢。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>setTimer</title>
<script>
var the_timer,the_image,x_position = 0;
function move_left(){
console.log("move_left() is running");
the_image = document.getElementById('cat');
console.log(the_image);
x_position = x_position + 1;
console.log(x_position);
the_image.style.left = x_position;
console.log(the_image.style.left);
the_timer = setTimeout(move_left,50);
}
</script>
</head>
<body onload="move_left()">
<img id="cat" src="7.png" style="height:150px;position:absolute;left:0">
</body>
</html>

最佳答案

您必须添加 px 或其他 CSS 单元才能获得所需的结果。当你通过 JS 改变 CSS 时。 CSS left 属性始终需要一个单位。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>setTimer</title>
<script>
var the_timer,the_image,x_position = 0;
function move_left(){
console.log("move_left() is running");
the_image = document.getElementById('cat');
console.log(the_image);
x_position = x_position + 1;
console.log(x_position);
the_image.style.left = x_position+"px";
console.log(the_image.style.left);
the_timer = setTimeout(move_left,50);
}
</script>
</head>
<body onload="move_left()">
<img id="cat" src="7.png" style="height:150px;position:absolute;left:0">
</body>
</html>

关于javascript - 尝试使 the_image.style.left = x_position;但日志显示结果不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35954502/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com