在 Javascript 中使用 setTimeout 移动文本不起作用

Moving text using setTimeout in Javascript not working

本文关键字:移动 文本 不起作用 setTimeout Javascript      更新时间:2023-09-26

你好,我正在做一个教程,文本"Yoo"应该向右移动,但它没有。泰

<!DOCTYPE html>
<html>
<head>
<script>
    var timer, x_pos=0, txt;
    function _timer() {
        txt = document.getElementById("txt");
        x_pos = x_pos+1;
        txt.style.left = x;
        timer = setTimeout(_timer, 50);
    }
</script>
</head>
<body onload="_timer()">
<h1 id="txt" style="position:absolute; left:0"> Yooo </h1>
</body>
</html>
变量

x 从未定义,您应该在px中提供left

txt.style.left = x_pos + "px";

<!DOCTYPE html>
<html>
<head>
<script>
    var timer, x_pos=0, txt;
    function _timer() {
        txt = document.getElementById("txt");
        x_pos = x_pos+1;
        txt.style.left = x_pos + "px";
        timer = setTimeout(_timer, 50);
    }
</script>
</head>
<body onload="_timer()">
<h1 id="txt" style="position:absolute; left:0"> Yooo </h1>
</body>
</html>

变量x从未定义。尝试:

txt.style.left = x_pos;

而不是

txt.style.left = x;

因此,您的最终代码是

<!DOCTYPE html>
<html>
<head>
<script>
    var timer, x_pos=0, txt;
    function _timer() {
        txt = document.getElementById("txt");
        x_pos = x_pos+1;
        txt.style.left = x_pos;
        timer = setTimeout(_timer, 50);
    }
</script>
</head>
<body onload="_timer()">
<h1 id="txt" style="position:absolute; left:0"> Yooo </h1>
</body>
</html>

你忘记添加单位:)

txt.style.left = x+'px';