我需要得到三個div的高度,將它們加在一起,看看滾動位置是否比這個數字大。現在我能夠獲得一個元素的高度,但我怎麼能添加其他元素呢?用jquery獲取多個div的高度
基本上,我想寫 「如果scroll_top比div的高度大於1 + DIV 2 + 3」
var scroll_top = $(window).scrollTop();
if ((scroll_top > $('.nav-bar-fixed').height()) {
alert('sometext');
}
我需要得到三個div的高度,將它們加在一起,看看滾動位置是否比這個數字大。現在我能夠獲得一個元素的高度,但我怎麼能添加其他元素呢?用jquery獲取多個div的高度
基本上,我想寫 「如果scroll_top比div的高度大於1 + DIV 2 + 3」
var scroll_top = $(window).scrollTop();
if ((scroll_top > $('.nav-bar-fixed').height()) {
alert('sometext');
}
試試這個:
$(document).ready(function() {
var limit =$('.myEle1').height() + $('.myEle2').height() + $('.myEle3').height();
$(window).scroll(function() {
var scrollVal = $(this).scrollTop();
if (scrollVal > limit) {
//do something.
}
});
});
爲什麼就不能呢?
var h = 0;
$('#div1, #div2, #div3').each(function(){ h+=$(this).height() });
這應該做的伎倆。
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);
}
你可以實現這種基於jQuery函數:
(function ($) {
$.fn.sumHeights = function() {
var h = 0;
this.each(function() {
h += $(this).height();
});
return h;
};
})(jQuery);
然後像這樣稱呼:
$('div, .className, #idName').sumHeights();
救了我寫下來! – 2015-07-31 14:42:11