簡體   English   中英

移動動態創建的按鈕JavaScript

[英]Move a button created dynamically JavaScript

我是一個初學者! 我已經動態創建了隨機數量的按鈕。 創建后,我希望它們自動開始移動。 由於某種原因,我的代碼創建了按鈕 ,但沒有使它們移動。 非常感謝!

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">

一些要點:

  • 每次迭代都會評估循環條件。 因此,您每次都與一個新的隨機數進行比較,因此按鈕數量的概率並不統一。
  • 您不需要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; } 

您的元素ID必須以字母([A-Za-z])開頭。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM