2013-02-08 82 views
1

我需要得到三个div的高度,将它们加在一起,看看滚动位置是否比这个数字大。现在我能够获得一个元素的高度,但我怎么能添加其他元素呢?用jquery获取多个div的高度

基本上,我想写 “如果scroll_top比div的高度大于1 + DIV 2 + 3”

var scroll_top = $(window).scrollTop(); 

if ((scroll_top > $('.nav-bar-fixed').height()) { 
    alert('sometext'); 
} 

回答

1

试试这个:

$(document).ready(function() { 
var limit =$('.myEle1').height() + $('.myEle2').height() + $('.myEle3').height(); 
    $(window).scroll(function() { 
     var scrollVal = $(this).scrollTop(); 
     if (scrollVal > limit) { 
      //do something. 
     } 
    }); 
});​ 

Here is a fixed nav samplesource.

8

为什么就不能呢?

var h = 0; 
$('#div1, #div2, #div3').each(function(){ h+=$(this).height() }); 
+0

救了我写下来! – 2015-07-31 14:42:11

4

这应该做的伎俩。

Working example on JS Bin

HTML:

<div class="nav-bar-fixed"></div> 
    <div class="nav-bar-fixed"></div> 
    <div class="nav-bar-fixed"></div> 

CSS:

.nav-bar-fixed { 
    height: 200px; 
} 

的JavaScript:

var scroll_top = $(window).scrollTop(), 
    $navBarFixed = $('.nav-bar-fixed'), 
    totalHeight = 0; 

$.each($navBarFixed, function() { 
    totalHeight += $(this).height(); 
}); 

if (scroll_top > totalHeight) { 
    alert(totalHeight); 
} 
1

你可以实现这种基于jQuery函数:

(function ($) { 
    $.fn.sumHeights = function() { 
     var h = 0; 
     this.each(function() { 
     h += $(this).height(); 
     }); 
     return h; 
    }; 
})(jQuery); 

然后像这样称呼:

$('div, .className, #idName').sumHeights();