document.getElementById(“ myB”)。style.top =“ 100px”;

时间:2019-05-20 12:49:09

标签: javascript html css

是否可以将style.top设置为变量而不是px?

当我将按钮按为随机值而不是常量时,我​​希望div更改绝对位置

<div class="dot" id="dot1" style="top:180px;left:280px"></div>

function myFunction1(){
    var x1 = Math.floor((Math.random() * 150) + 75);
    var y1 = Math.floor((Math.random() * 150) + 75);

    console.log(x1);
    console.log(y1);


   //this works
   document.getElementById("dot1").style.top = "100px";
   document.getElementById("dot1").style.top = "100px";

   //this doesnt
   document.getElementById("dot1").style.top = x1;
   document.getElementById("dot1").style.top = y1;
   }

1 个答案:

答案 0 :(得分:0)

document.documentElement.style.top = x1。左属性也一样。