[英]How do I add class to body when div height is smaller than window?
I'm trying to add a class to the body if a certain divs height is smaller than the users window size. 如果某个div高度小于用户窗口的大小,我正在尝试向主体添加一个类。 Here is my current jQuery script.
这是我当前的jQuery脚本。 It doesn't work very well, and I don't get any errors.
它不能很好地工作,我也没有任何错误。 Not sure what I'm doing wrong.
不知道我在做什么错。
Thanks 谢谢
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);
});
Try this... no need to create separate function : 试试这个...无需创建单独的函数:
$(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');
}
});
Generally, the code looks ok. 通常,代码看起来还可以。 But if your
$('.wrap')
has margins or borders, you might want to use use .outerHeight()
instead of .height()
. 但是,如果您的
$('.wrap')
具有边距或边框,则可能要使用.outerHeight()
而不是.height()
。
Here's a fiddle that shows what's going on: 这是一个小提琴,它显示了正在发生的事情:
http://jsfiddle.net/4fqb8t1q/ http://jsfiddle.net/4fqb8t1q/
$(document).ready(function() {
checkWidth();
$(window).resize(checkWidth);
});
function checkWidth() {
var $pageHeight = $('.wrap').height();
alert($(window).height() + " < " + $pageHeight);
if ($(window).height() < $pageHeight) {
$('body').addClass('need-padding');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.