简体   繁体   中英

My div won't change width with my javascript function

I have made a makeshift progress bar with two divs, styled with css to fit one in another to make the progress bar. I have a button that changes the width of the inside div to go up when I click the button, but the button click does not change the width of the div. I made sure I made no errors, the javascript console in my chrome browser gives no errors when I click the button. Anyways, here is my code:

 function clickMe() { var newExp = parseInt(document.getElementById("expHold").innerHTML); document.getElementById("bar2").style.width = newExp + 'px'; document.getElementById("expHold").innerHTML += '+1'; document.getElementById("expHold").innerHTML = eval(document.getElementById("expHold").innerHTML); } 
 #bar1 { border: 2px solid gold; height: 15px; width: 100px; background-color: blue; border-radius: 8px; } #bar2 { height: 15px; width: 1px; background-color: skyblue; border-radius: 8px; } 
 <div id="bar1"> <div id="bar2"> </div> </div> <p> <input type="button" value="Click me" onClick="clickMe()" /> <span id="expHold" style="color:black;">1</span> 

I would appreciate any help telling me what I am doing wrong, thanks!

  1. Please do not use inline JavaScript. It reduces readability and maintainability.
  2. You should use a JavaScript variable to store the exp , this way you don't have to repeatedly query the DOM, which is process intensive.
  3. You should cache the DOM objects instead of creating new ones on each iteration.
  4. You can increment the previously created exp variable by using the prefix increment modifier
    • The prefix increment modifier will return the incremented value.
    • The postfix increment modifier will return the value before incrementing.

 var exp = 0, current; var bar1 = document.getElementById("bar1"); var bar2 = document.getElementById("bar2"); var hold = document.getElementById("expHold"); var max = bar1.clientWidth; document.getElementById('my-button').onclick = function() { // Don't go past the end. if(bar2.clientWidth < max) { current = ++exp; hold.textContent = current; bar2.style.width = current + 'px'; } } 
 #bar1 { border: 2px solid gold; height: 15px; width: 100px; background-color: blue; border-radius: 8px; } #bar2 { height: 15px; width: 0px; background-color: skyblue; border-radius: 8px; } 
 <div id="bar1"> <div id="bar2"> </div> </div> <p> <input type="button" value="Click me" id="my-button" /> <span id="expHold" style="color:black;">0</span> 

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