首先,檢查元素的可見性:
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);
});
奇拉格拉溫德拉太謝謝你了:) –
你是最歡迎的。如果它回答你的問題,請接受答案:) –