Changing the position of element with Javascript

前端 未结 2 1867
生来不讨喜
生来不讨喜 2021-01-22 05:12

This is supposed to change the position of a paragraph (with the id \'Text\') more to the right each time it is looped. It doesn\'t work though and I can\'t figure out how to fi

相关标签:
2条回答
  • 2021-01-22 05:45

    You have 2 issues here.

    1) You have never defined d. That causing to stop the script right there without executing next lines of code.

    2) You have never called myLoop() function.

    So with all corrections.

    var x = 0;
    var d = document.getElementById('Text');
    d.style.position = "absolute";
    myLoop();
      function myLoop () {
        setTimeout(function () {
          x += 10;
          d.style.left = x+'px';
          myLoop();
        }, 100)
      }
    <div id="Text">Test </div>

    Besides this solution, you might have a to take a look at setInterval function which reduce your code a bit.

    var x = 0;
    var d = document.getElementById('Text');
    d.style.position = "absolute";
    myLoop();
      function myLoop () {
        setInterval(function () {
          x += 10;
          d.style.left = x+'px';
        }, 100)
      }
    <div id="Text">Test </div>

    0 讨论(0)
  • 2021-01-22 05:55

    try this one

    d have not any value so define d with

    d = document.getElementById('Text');

    and call your function myLoop so its work

    var x = 0;
    d = document.getElementById('Text');
    d.style.position = "absolute";
    myLoop();
    
    function myLoop() {
      setTimeout(function() {
        x += 10;
        d.style.left = x + 'px';
        myLoop();
      }, 100)
    }
    <input type='text' id='Text'>

    0 讨论(0)
提交回复
热议问题