Get height of multiple divs with jquery

2019-07-25 11:11发布

I need to get the height of three divs, add them together and see if the scroll position is great than that number. Right now I am able to get the height of one element, but how could I add others in?

Basically, I want to write "if scroll_top is greater than the height of div 1 + div 2 + 3"

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

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

4条回答
你好瞎i
2楼-- · 2019-07-25 11:30

Why not simply this ?

var h = 0;
$('#div1, #div2, #div3').each(function(){ h+=$(this).height() });
查看更多
▲ chillily
3楼-- · 2019-07-25 11:32

Try this:

$(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 sample and source.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-07-25 11:39

This should do the trick.

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);
}
查看更多
我欲成王,谁敢阻挡
5楼-- · 2019-07-25 11:39

You could implement this JQuery based function:

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

And then call it like this:

$('div, .className, #idName').sumHeights();
查看更多
登录 后发表回答