在Javascript中使用setTimeout移动文本无效
您好,我正在做一个教程,文本“Yoo”应该向右移动,但它没有。泰在Javascript中使用setTimeout移动文本无效,javascript,html,Javascript,Html,您好,我正在做一个教程,文本“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;
<!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_pos=0,txt;
函数_timer(){
txt=document.getElementById(“txt”);
x_pos=x_pos+1;
txt.style.left=x;
定时器=设置超时(定时器,50);
}
哟
变量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>
变量计时器,x_pos=0,txt;
函数_timer(){
txt=document.getElementById(“txt”);
x_pos=x_pos+1;
txt.style.left=x_pos;
定时器=设置超时(定时器,50);
}
哟
变量x从未定义过,您应该在px
中提供左侧的
txt.style.left = x_pos + "px";
变量计时器,x_pos=0,txt;
函数_timer(){
txt=document.getElementById(“txt”);
x_pos=x_pos+1;
txt.style.left=x_pos+“px”;
定时器=设置超时(定时器,50);
}
哟
您忘记添加单位:)
更改txt.style.left=x;to txt.style.left=x_pos;是的,当我改变变量时,我错过了,我认为x可能是一些特殊的变量,我错过了‘px’,但是的,谢谢你也需要修正它
txt.style.left = x+'px';