[英]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. 我制作了一个带有两个div的临时进度条,并使用css进行样式设置以使其相互适应以制作进度条。 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. 我有一个按钮,可在单击按钮时更改内部div的宽度,但是单击按钮不会更改div的宽度。 I made sure I made no errors, the javascript console in my chrome browser gives no errors when I click the button. 我确保没有做任何错误,当我单击按钮时,Chrome浏览器中的javascript控制台也没有出现错误。 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! 感谢您告诉我我做错了什么,谢谢!
exp
, this way you don't have to repeatedly query the DOM, which is process intensive. 您应该使用JavaScript变量来存储exp
,这样您就不必重复查询DOM了(这是过程密集型的)。 exp
variable by using the prefix increment modifier 您可以使用前缀递增修饰符来递增先前创建的exp
变量
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.