使用javascript更改id宽度百分比

时间:2016-02-22 19:05:05

标签: javascript html css

我正在尝试编写一个百分比目标栏。我似乎无法在javascript中更改#bar宽度百分比。任何建议?对不起凌乱的代码。我有一个-20 * -1的原因。我只需要集中精力来改变id宽度百分比。

CSS:

.graph {
  width: 500px; /* width and height are arbitrary, just make sure the #bar styles are changed accordingly */
  height: 30px;
  border: 1px solid #888; 
  background: rgb(168,168,168);
  position: relative;
}
#bar {
  height: 29px; /* Not 30px because the 1px top-border brings it up to 30px to match #graph */
  width: 34%;
  float: left;
  background: rgb(255,197,120); 
  border-top: 1px solid #fceabb;
}

JS:

var _first = -20 * -1;
var _second = 150;
var _third = _first / _second * 100;
document.getElementById('bar').style.width = _third + "%";

HTML:

<center><div id="progress" class="graph"><div id="bar"></div></div></center>

2 个答案:

答案 0 :(得分:2)

因为在DOM准备就绪之前加载了JS,所以找不到尚未加载的div bar,你应该把你的代码放在onload函数中:< / p>

window.onload=function(){
    var _first = -20 * -1;
    var _second = 150;
    var _third = _first / _second * 100;

    document.getElementById('bar').style.width = _third + "%";
}

希望这有帮助。

答案 1 :(得分:0)

你的代码是对的。刚刚失灵。当您的JavaScript尝试操作DOM时,浏览器尚未创建它。有两种方法可以做到这一点,这就是我这样做的方式。我喜欢这种方式,因为不需要调用额外的函数来等待创建DOM。

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <style>
        .graph {
            width: 500px;
            height: 30px;
            border: 1px solid #888; 
            background: rgb(168,168,168);
            position: relative;
        }
        #bar {
            height: 29px;
            width: 34%;
            float: left;
            background: rgb(255,197,120); 
            border-top: 1px solid #fceabb;
        }
    </style>
    <!-- The HTML needs to come before the JavaScript. That way
          the DOMS are created for the JavaScript  -->
    <center>
        <div id="progress" class="graph">
            <div id="bar"></div></div>
    </center>

    <script>
        var _first = -20 * -1;
        var _second = 150;
        var _third = _first / _second * 100;
        document.getElementById('bar').style.width = _third + "%";
    </script>
</body>
</html>