简体   繁体   中英

Change id width percentage with javascript

I'm trying to code a percentage goal bar. I can't seem to change the #bar width percentage in javascript. Any advice?? Sorry for the messy code. I have a reason for the -20 * -1. I just need to focus getting the id width percentage to change.

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>

Because the JS is loaded before the DOM is ready it could not find the div withe id bar that is not loaded yet, you should put your code inside onload function :

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

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

Hope this helps.

Your code is right. Just out of order. When your JavaScript tries to manipulate the DOM, it is not yet created by the browser. There are two ways of doing it and here is the way I do it. I like this way because there is not the need for an extra function to be called in order to wait for the DOM to be created.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM