简体   繁体   English

无法使用jQuery动态设置Div的高度

[英]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? 您能否看一下这个演示 ,让我知道为什么我不能动态设置.box的高度?

$(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-' . 代替$(“。box”),使用$(“ [id ^ ='box-']”)-您不是要查找具有“ box”类的对象,而是要查找具有id属性(以字符串开头)的对象'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.) (或者,您可以为每个要调整大小的元素添加一个“ box”类,并保留原始的jQuery选择器;也许这是一种更好的方法,它取决于网站其余部分的逻辑。您可以决定。)

  1. $("[id^='box-']") $( “[ID ^ = '箱 - ']”)
  2. $(".box") and divs like class="col-md-12 box" $(“。box”)和divs,例如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". 您需要查询名为“ col-md-12”的类。

Then, you are using the window.load() event which was removed from JQuery in 3.0 (see here ). 然后,您正在使用window.load()事件,该事件已从3.0中的JQuery中删除(请参阅此处 )。 You can either use $(document).ready(function() {}) or $(window).on("load",function(){}) 您可以使用$(document).ready(function() {})$(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'});
    });
});

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

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