【问题标题】:document.getElementById("myB").style.top = "100px"; [duplicate]document.getElementById("myB").style.top = "100px"; [复制]
【发布时间】:2019-10-06 20:23:25
【问题描述】:

有没有办法将 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;
   }

【问题讨论】:

  • 检查是否对您有帮助:w3schools.com/js/js_htmldom_css.asp
  • 你应该将属性设置为document.getElementById('dot1').style.setProperty(...
  • x1y1 是变量,所以你不应该在它们周围加上引号
  • 我也没有让它工作:document.getElementById('dot1').style.setProperty('top',x1)
  • 您可以根据需要使用变量。 CSS 中的长度仍然需要单位,因此变量必须包含单位。

标签: javascript html css


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-12-24
    • 2012-07-01
    • 2014-11-13
    • 2015-02-26
    • 2012-10-22
    • 2016-04-19
    • 1970-01-01
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多