簡體   English   中英

當div高度小於window時,如何向正文添加類?

[英]How do I add class to body when div height is smaller than window?

如果某個div高度小於用戶窗口的大小,我正在嘗試向主體添加一個類。 這是我當前的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);
});

試試這個...無需創建單獨的函數:

 $(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');
        }
  });

通常,代碼看起來還可以。 但是,如果您的$('.wrap')具有邊距或邊框,則可能要使用.outerHeight()而不是.height()

這是一個小提琴,它顯示了正在發生的事情:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM