移动一个动态创建的按钮JavaScript

时间:2015-05-18 20:28:59

标签: javascript javascript-events

我是一个非常初学者! 我已经动态创建了一个随机数量的按钮。创建之后,我希望它们自动开始移动。 出于某种原因,我的代码会创建按钮,但不会让它们移动。  非常感谢!

javascript.js

function myFunction() {
    for (i = 1; i<=Math.random() * 10; i++){
            var x = document.createElement("button");
            x.id = i;
            x.innerHTML = i;

            document.body.appendChild(x);
            moveMe(x.id);
            var v1 = Math.floor(Math.random() * 255);
            var v2 = Math.floor(Math.random() * 255);
            var v3 = Math.floor(Math.random() * 255);
            x.style.backgroundColor = "rgb(" + v1 + "," + v2 + "," + v3 + ")";

        }
}

function uMM(id){
    var x = document.getElementById(id);
    x.pozx = x.pozx + 1;
    x.pozy = x.pozy + 1;
    x.style.left = x.pozx + "px";
    x.style.top = x.pozy + "px";

}
function moveMe(id){
    var x = document.getElementById(id);
    x.pozx = 0;
    x.pozy = 0;
    setInterval( "uMM(" + id + ")", 1000);
}

home.php

<input type="text" id="demo">

2 个答案:

答案 0 :(得分:3)

有些观点:

  • 在每次迭代时评估循环条件。因此,您每次都将新的随机数进行比较,因此按钮数量的概率不均匀。
  • 您不需要ID。只需将对元素的引用作为参数或this值传递。
  • 不要将setTimeoutsetInterval与字符串一起使用,因为它就像邪恶的eval!相反,请使用函数。

(function myFunction() {
  for (var i=1, l=Math.random()*10; i<=l; ++i){
    var x = document.createElement("button");
    x.innerHTML = i;
    document.body.appendChild(x);
    moveMe(x);
    var rgb = Array.apply(null, Array(3)).map(function() {
      return Math.floor(Math.random() * 255);
    }).join(',');
    x.style.backgroundColor = "rgb(" + rgb + ")";
  }
})();
function uMM(){
  var x = this;
  x.style.left = ++x.pozx + "px";
  x.style.top = ++x.pozy + "px";
}
function moveMe(x){
  x.pozx = x.pozy = 0;
  setInterval(uMM.bind(x), 1e3);
}
button {
  position: relative;
}

答案 1 :(得分:0)

您的元素ID必须以字母([A-Za-z])开头。

var x = document.createElement("button");
x.id = 'dyn-button-' + i;
相关问题