Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 当div高度小于window时,如何向body添加类?_Javascript_Jquery_Resize - Fatal编程技术网

Javascript 当div高度小于window时,如何向body添加类?

Javascript 当div高度小于window时,如何向body添加类?,javascript,jquery,resize,Javascript,Jquery,Resize,如果某个divs高度小于用户窗口大小,我将尝试向主体添加一个类。这是我当前的jQuery脚本。它不太好用,我也没有收到任何错误。不知道我做错了什么 谢谢 jQuery(document).ready(function($) { var $window = $(window); var $pageHeight = $('.wrap').height(); function checkWidth() { var windowsize = $window.hei

如果某个divs高度小于用户窗口大小,我将尝试向主体添加一个类。这是我当前的jQuery脚本。它不太好用,我也没有收到任何错误。不知道我做错了什么

谢谢

jQuery(document).ready(function($) {
    var $window = $(window);
    var $pageHeight = $('.wrap').height();
    function checkWidth() {
        var windowsize = $window.height();
        if (windowsize < $pageHeight) {
            $('body').addClass('need-padding');
        }
    }
    checkWidth();   
    $(window).resize(checkWidth);
});
jQuery(文档).ready(函数($){
变量$window=$(window);
var$pageHeight=$('.wrap').height();
函数checkWidth(){
var windowsize=$window.height();
如果(窗口大小<$pageHeight){
$('body').addClass('need-padding');
}
}
检查宽度();
$(窗口)。调整大小(选中宽度);
});

通常,代码看起来正常。但是,如果您的
$('.wrap')
有边距或边框,您可能希望使用
.outerHeight()
而不是
.height()

,下面是一个显示发生了什么的小提琴:

$(文档).ready(函数(){
检查宽度();
$(窗口)。调整大小(选中宽度);
});  
函数checkWidth(){
var$pageHeight=$('.wrap').height();
警报($(窗口).height()+“<”+$pageHeight);
如果($(窗口).height()<$pageHeight){
$('body').addClass('need-padding');
}
}

试试这个。。。无需创建单独的函数:

 $(window).resize(function(){
     var $windowHeight = $(window).height();
     var $blockHeight = $('.wrap').height();
        if ($blockHeight < $windowHeight ) {
            //console.log($windowHeight+" Window Height");
            //console.log($blockHeight+" Block Height");
            $('body').addClass('need-padding');
        }
  });
$(窗口)。调整大小(函数(){
var$windowHeight=$(window.height();
变量$blockHeight=$('.wrap').height();
如果($blockHeight<$windowHeight){
//console.log($windowHeight+“windowHeight”);
//console.log($blockHeight+“Block Height”);
$('body').addClass('need-padding');
}
});

据我所知,当窗口大小小于具有类“wrap”的div时,您正在添加类“need padding”——>
 $(window).resize(function(){
     var $windowHeight = $(window).height();
     var $blockHeight = $('.wrap').height();
        if ($blockHeight < $windowHeight ) {
            //console.log($windowHeight+" Window Height");
            //console.log($blockHeight+" Block Height");
            $('body').addClass('need-padding');
        }
  });