2016-03-12 2 views
-1

Привет, я делаю учебник, и текст «Yoo» предполагает движение вправо, но это не так. TyПеремещение текста с помощью setTimeout в Javascript не работает

<!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> 
+0

изменение txt.style.left = х; to txt.style.left = x_pos; – harry

ответ

0

переменной х никогда не определяется, и вы должны обеспечить left в px, как

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>

+0

yeee it work thanks broo –

0

Переменная 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> 
+0

Да, я пропустил это, когда я менял переменные, думал, что x может быть какой-то специальной переменной, я пропустил 'px', но да, спасибо, вам нужно исправить это тоже –

0

нужно было забыть добавить блок :)

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

sweeet it work thanks dudes –

Смежные вопросы