admin管理员组文章数量:1391943
I am trying to make a div expand as the user presses a button over and over again.
<script>
heartClicks=10;
function love(){
heartClicks++;
}
</script>
How can I set the width of the div equal to heartClicks?
<div id="luv"></div>
I am trying to make a div expand as the user presses a button over and over again.
<script>
heartClicks=10;
function love(){
heartClicks++;
}
</script>
How can I set the width of the div equal to heartClicks?
<div id="luv"></div>
Share
Improve this question
edited Sep 26, 2013 at 23:51
Thought Space Designs
4291 gold badge5 silver badges17 bronze badges
asked Sep 26, 2013 at 23:25
user2821453user2821453
111 silver badge2 bronze badges
3
- 2 you mean how to set the width of the div depending on the heartClicks variable? – Krimson Commented Sep 26, 2013 at 23:31
- Are you asking how to set the div width to the value of a JavaScript variable, or are you asking how to set the JavaScript variable to the value of the div's width? Your title asks for one, but the question itself asks for the other. – doppelgreener Commented Sep 26, 2013 at 23:33
- if you want to make the div expand based on how many times the user clicks, you will need to dynamically change the width of the div, not set the heartClicks equal to the width of the div. I made this assumption in my answer. I assumed it was a typo but correct me if I'm wrong. – aug Commented Sep 26, 2013 at 23:36
4 Answers
Reset to default 3document.getElementById('luv').style.width = heartClicks + "px";
document.getElementById("luv").style.width = heartClicks + "px";
Something to keep in mind is you're going to need to reset/reapply the style everytime they click so you might want to stick this in your button click function.
var heartClicksElement = document.querySelector("#luv");
heartClicks = heartClicksElement.style.width;
@aug's answer is great for standard javascript (make sure you have an event handler). If you want to use jQuery (or if anyone else browsing this question wants to use jQuery) try the following:
var heartClicks=10;
$(function(){
$('#expand').on("click",function(){
heartClicks++;
$('#luv').css({'width':heartClicks});
});
});
Try it out with this working fiddle.
本文标签: htmlHow do I set a div width equal to a Javascript variableStack Overflow
版权声明:本文标题:html - How do I set a div width equal to a Javascript variable? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744707651a2620935.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论