【问题标题】:changing css background color with javascript variables使用 javascript 变量更改 css 背景颜色
【发布时间】:2015-02-27 19:53:45
【问题描述】:

我正在尝试将 div 'changebox' 设置为 rgb 的颜色,这是三个随机的结果。 rgb 正在改变,(我可以通过 document.writes 看出),但无论 rgb 是什么,div 都保持白色。请帮助将框更改为正确的 rgb 颜色。

<div id="changeBox" style="width: 150px; height: 150px; position: absolute; top: 10%; left: 10%; background-color: white; border: 4px solid black; color: black; font-family: 'Merriweather Sans', sans-serif;">

<script>
var randR = Math.floor(Math.random() * 255) + 1;
document.write(randR+", ");
var randG = Math.floor(Math.random() * 255) + 1;
document.write(randG+", ");
var randB = Math.floor(Math.random() * 255) + 1;
document.write(randB);

document.getElementById('changeBox').style = "background-color: rgb(" + randR + ", " + randG + ", " + randB + ");";
</script>

</div>

【问题讨论】:

    标签: javascript css variables


    【解决方案1】:

    您应该只更改background-color 属性:

    document.getElementById('changeBox').style.backgroundColor = "rgb(" + randR + ", " + randG + ", " + randB + ")";
    

    在这种情况下,删除拖尾 ; 以使值有效。

    演示: http://jsfiddle.net/zc16vmjt/

    另一件事是document.write 不是很好的做法。在这种情况下很容易避免它并使用appendChild

    var box = document.getElementById('changeBox');
    var randR = Math.floor(Math.random() * 255) + 1;
    var randG = Math.floor(Math.random() * 255) + 1;
    var randB = Math.floor(Math.random() * 255) + 1;
    box.appendChild(document.createTextNode(randR + ", " + randG + ", " + randB));
    box.style.backgroundColor = "rgb(" + randR + ", " + randG + ", " + randB + ")";
    

    演示: http://jsfiddle.net/zc16vmjt/1/

    【讨论】:

      【解决方案2】:

      不要直接分配给style。分配给style.backgroundColor

      【讨论】:

      • 感谢您的帮助,但每个 rgb 的颜色仍然没有改变
      【解决方案3】:

      每次你:

      document.write();
      

      您正在覆盖整个文档正文中的内容,完全删除了 div。

      var randR = Math.floor(Math.random() * 255) + 1;
      var randG = Math.floor(Math.random() * 255) + 1;
      var randB = Math.floor(Math.random() * 255) + 1;
      
      document.getElementById('changeBox').style.backgroundColor = "rgb(" + randR+ "," + randG+ "," + randB + ")";
      

      试试这个,你应该没问题。如果要查看值,请输出到单独的 div;只是不要用 document.write() 覆盖整个文档;

      【讨论】:

      • 这不太正确:“您正在覆盖整个文档正文中的内容,完全删除了 div”document.write 仅当文档已经关闭时才会覆盖所有内容,这意味着 DOM 已加载并呈现。在 OP 的情况下,document.write 执行时正在加载文档,因此它确实附加了内容,而不是覆盖它。但这当然是一种不好的做法。
      【解决方案4】:

      您有一个额外的分号,并且缺少一个右引号。

      要跟踪嵌套引号,最好在单引号和双引号之间交替使用。这样做可以更容易地意识到,在右括号之后,应该有一个引号来结束它,并且后​​面应该有一个与开始的引号相匹配的引号,在 background-color 之前。

      var theBox = document.getElementById('changeBox');
      theBox.style = "background-color: rgb('+ randR+ ',' +randG+ ','+randB+')'";
      

      【讨论】:

        猜你喜欢
        • 2017-08-15
        • 1970-01-01
        • 1970-01-01
        • 2016-07-22
        • 2013-04-28
        • 2012-07-10
        • 2015-06-23
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多