简体   繁体   中英

How do I set a div width equal to a Javascript variable?

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>
document.getElementById('luv').style.width = heartClicks + "px";
document.getElementById("luv").style.width = heartClicks + "px";

需要记住的是,每次单击时您都需要重置/重新应用样式,这样您可能希望在按钮单击功能中坚持使用它。

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 .

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