简体   繁体   中英

Not Able to Set Height Of Div Dynamically using jQuery

Can you please take a look at this demo and let me know why I am not able to set the height of .box dynamically?

$(function(){
    $(window).load(function(){ // On load
        $('.box').css({'height':(($(window).height()))+'px'});
    });
    $(window).resize(function(){ // On resize
        $('.box').css({'height':(($(window).height()))+'px'});
    });
});

<section>
<div class="col-md-12" id="box-1">Height has been set!</div>
</section>
<section>
<div class="col-md-12" id="box-2">Height has been set!</div>
</section>
<section>
<div class="col-md-12" id="box-3">Height has been set!</div>
</section>
<section>
<div class="col-md-12" id="box-4">Height has been set!</div>
</section>
<section>
<div class="col-md-12" id="box-5">Height has been set!</div>
</section>

You're referring to a class that's not present. Instead of $(".box"), use $("[id^='box-']") - you're not looking for the ones with "box" class but the ones with an id property starting with the string 'box-' .

(Alternatively, you could add a "box" class to each element you want to size and leave the original jQuery selector; maybe it's a better approach, it depends on the logic of the rest of your site. You decide.)

  1. $("[id^='box-']")
  2. $(".box") and divs like class="col-md-12 box"

First, you are using the wrong selector. You need to query for your class which is named "col-md-12".

Then, you are using the window.load() event which was removed from JQuery in 3.0 (see here ). You can either use $(document).ready(function() {}) or $(window).on("load",function(){})

Your code should look like this:

$(function(){
    $(document).ready(function(){ // On load
        $('.col-md-12').css({'height':(($(window).height()))+'px'});
    });
    $(window).resize(function(){ // On resize
        $('.col-md-12').css({'height':(($(window).height()))+'px'});
    });
});

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