我正在使用此脚本隐藏div并在滚动浏览页面中的某个点时显示它。这工作正常,但当我向上滚动到顶部时,div保持可见。任何人都可以帮我修改一下我可以对代码进行修改,以便在向上滚动到所需点之上时再次隐藏div吗?
谢谢,T
$(document).ready( function() {
$("#dvid").hide(); //hide your div initially
var topOfOthDiv = $("#othdiv").offset().top;
$(window).scroll(function() {
if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
$("#dvid").show(); //reached the desired point -- show div
}
});
});
答案 0 :(得分:1)
$(document).ready( function() {
$("#dvid").hide(); //hide your div initially
var topOfOthDiv = $("#othdiv").offset().top;
$(window).scroll(function() {
if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
$("#dvid").show(); //reached the desired point -- show div
}
else{
$("#dvid").hide(); //else above the desired point -- hide div
}
});
});
答案 1 :(得分:0)
首先,检查元素可见性:
var rect = element.getBoundingClientRect();
var visible = Boolean(
rect.top >= 0
&& rect.left >= 0
&& rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)
&& rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
然后绑定事件以重新验证可见性:
jQuery(window).bind('DOMContentLoaded load resize scroll', fn);
// fn - is your function to show/hide elements in accordance with previous statement
所以,最终的代码是:
$(document).ready( function() {
var checkVisibility = function () {
$("#dvid, #othdiv").each(function () {
var rect = this.getBoundingClientRect(),
visible = Boolean(
rect.top >= 0
&& rect.left >= 0
&& rect.bottom <= (window.innerHeight || document.documentElement.clientHeight)
&& rect.right <= (window.innerWidth || document.documentElement.clientWidth)
);
$(this)[visible ? 'show' : 'hide']();
});
};
//hide your divs initially
$("#dvid, #othdiv").hide();
jQuery(window).bind('DOMContentLoaded load resize scroll', checkVisibility);
});
答案 2 :(得分:0)
$(document).ready( function() {
$("#dvid").hide(); //hide your div initially
var topOfOthDiv = $("#othdiv").offset().top;
$(window).scroll(function() {
if($(window).scrollTop() > topOfOthDiv) { //scrolled past the other div?
$("#dvid").show(); //reached the desired point -- show div
} else {
$("dvid").show(); //hide div
}
});
});