[英]Hide an element when scroll to specific class
我用這個 JQuery 代碼有一個粘性“轉到頂部”按鈕:
//sticky back-to-top button
(function (t) {
t(window).bind("scroll", function () {
500 < t(this).scrollTop()
? t(".back-to-top").fadeIn(400)
: t(".back-to-top").fadeOut(400);
}),
t(".back-to-top").click(function () {
t("html, body").animate({ scrollTop: "0px" }, 500);
});
})(jQuery);
此代碼正常工作。 但我想當這個粘性按鈕到達一個名為“go-top”的特定 class 時消失。 對不起,我的英語不好。
您可以使用攔截觀察器,因此當具有所述 class 的目標元素在視圖中時,它會觸發回調以隱藏按鈕。
示例:代碼可能不准確,但它旨在指出要遵循的方向。
let options = {
root: document.querySelector('.go-top'),
rootMargin: '0px',
threshold: 1.0
}
let prevRatio = 0.0;
let observer = new IntersectionObserver(callback, options);
let target = document.querySelector('#back-to-top-button');
observer.observe(target);
function handleIntersect(entries, observer) {
entries.forEach((entry) => {
if (entry.intersectionRatio > prevRatio) {
entry.target.style.display = "none";
} else {
entry.target.style.backgroundColor = "block";
}
prevRatio = entry.intersectionRatio;
});
}
讓我知道事情的后續...
您可以將root
切換到null
但這會使按鈕在具有 class 的元素在視口中時消失
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.