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
Add a ment  | 

4 Answers 4

Reset to default 3
document.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