使用Javascript更改元素的位置 [英] Changing the position of element with Javascript

查看:647
本文介绍了使用Javascript更改元素的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该在每次循环时将段落(带有id为文本")的位置更向右移.但是它不起作用,我也不知道如何解决它,所以如果有人可以帮助我,我将非常高兴.预先谢谢你.

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 fix it, so I would be very happy if someone could help me. Thank you in advance.

  var x = 0;

  d.style.position = "absolute";

  function myLoop () {
    setTimeout(function () {
      x += 10;
      document.getElementById('Text').style.left = x+'px';
      myLoop();
    }, 100)
  }

(这是脚本中的所有内容)

(This is everything in the script)

推荐答案

您在这里有2个问题.

1)您从未定义d.这导致在不执行下一行代码的情况下就停止了脚本.

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

2)您从未调用过myLoop()函数.

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>

除了此解决方案之外,您可能还需要看一下setInterval函数,该函数可以减少代码.

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>

这篇关于使用Javascript更改元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆