我在这个页面上工作。主要结构是一些彼此之下的DIV。当用户从一个滚动到另一个时,我需要做一些过渡或动画。 DIV的高度不一样。它仅由最小高度:100%完成。当我在DIV结束时尝试做任何警报时,我的JS不起作用。
<div id="page">
<div class="section section_1"> ...content...</div>
<div class="section section_2">...content...</div>
<div class="section section_3">...content...</div>
<div class="section section_4">...content...</div>
</div>
这是JS文件
jQuery(
$('.section').on('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) {
alert('end of div');
}
})
);
你有什么想法,为什么这不起作用?或者你能告诉我任何其他解决方案如何制作这种动画吗?
答案 0 :(得分:2)
问题已经得到解答here。
<强>被修改强>
绑定您的alert
:
var shown = document.getElementById("page").children;
function callback () {
alert('end of div');
}
function isElementInViewport(el) {
var eap,
rect = el.getBoundingClientRect(),
docEl = document.documentElement,
vWidth = window.innerWidth || docEl.clientWidth,
vHeight = window.innerHeight || docEl.clientHeight,
efp = function (x, y) { return document.elementFromPoint(x, y) },
contains = "contains" in el ? "contains" : "compareDocumentPosition",
has = contains == "contains" ? 1 : 0x14;
// Return false if it's not in the viewport
if (rect.right < 0 || rect.bottom < 0
|| rect.left > vWidth || rect.top > vHeight)
return false;
// Return true if any of its four corners are visible
return (
(eap = efp(rect.left, rect.top)) == el || el[contains](eap) == has
|| (eap = efp(rect.right, rect.top)) == el || el[contains](eap) == has
|| (eap = efp(rect.right, rect.bottom)) == el || el[contains](eap) == has
|| (eap = efp(rect.left, rect.bottom)) == el || el[contains](eap) == has
);
}
function fireIfElementVisible (el, callback) {
return function () {
if ( isElementInViewport(el) ) {
callback();
}
}
}
var handler = fireIfElementVisible (shown[shown.length - 1], callback);
$(document).on('DOMContentLoaded load resize scroll', handler);
上面的函数将返回布尔值,表示您的元素当前是否在屏幕上可见。
答案 1 :(得分:2)
试试这个:
jQuery(function($) {
$('.section').bind('scroll', function() {
if($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
alert('end reached');
}
})
});