【问题标题】:Get height of multiple divs with jquery使用jquery获取多个div的高度
【发布时间】:2017-11-23 23:35:16
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: jquery jquery-selectors


    【解决方案1】:

    为什么不简单呢?

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

    【讨论】:

    • 让我免于写它!
    【解决方案2】:

    这应该可以解决问题。

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

    【讨论】:

      【解决方案3】:

      试试这个:

      $(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.

      【讨论】:

        【解决方案4】:

        你可以实现这个基于 JQuery 的函数:

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

        然后这样称呼它:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-09-06
          • 2014-01-19
          • 2012-02-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多