简体   繁体   English

如何设置div宽度等于Javascript变量?

[英]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. 当用户一遍又一遍地按下按钮时,我试图使div扩展。

    <script>
            heartClicks=10;
            function love(){
                heartClicks++;
            }
      </script>

How can I set the width of the div equal to heartClicks? 如何设置div的宽度等于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). @ aug的答案很适合标准的javascript(确保你有一个事件处理程序)。 If you want to use jQuery (or if anyone else browsing this question wants to use jQuery) try the following: 如果你想使用jQuery(或者如果其他人浏览这个问题想要使用jQuery),请尝试以下方法:

var heartClicks=10;

$(function(){
    $('#expand').on("click",function(){
        heartClicks++;
        $('#luv').css({'width':heartClicks});
    });
});

Try it out with this working fiddle . 尝试用这个工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM