Get height of multiple divs with jquery

我是研究僧i 提交于 2020-01-16 01:13:12

问题


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

回答1:


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.




回答2:


Why not simply this ?

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



回答3:


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);
}



回答4:


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();


来源:https://stackoverflow.com/questions/14782087/get-height-of-multiple-divs-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!