[英]Preventing scroll event when clicking an anchor bookmark
單擊錨書簽會觸發滾動事件。
如何僅在用戶滾動時而不是在單擊書簽鏈接時觸發回調?
注意: 一個措辭不佳且有答案的問題已經關閉,但是我認為它對社區仍然有用,因為我在StackOverflow上沒有看到類似的問題
Shomz解決方案依賴於文檔滾動上下文中的錨元素。 如果該元素不在文檔的滾動上下文中,則偏移量檢查可能會失敗:
<body>
<div style="max-height: 200px; overflow: auto">
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<a name="myanchor">anchor</a>
</body>
我認為還有其他解決方案:
去抖
檢測何時單擊了錨鏈接( hashchange
/ onclick
)並hashchange
scroll
事件。
var debounce = false;
window.addEventListener("hashchange", function () { // also add one for `onclick`
debounce = true;
setTimeout(function () {
debounce = false;
}, 1);
});
window.addEventListener("scroll", function () {
if (debounce) {
return;
}
// .. handle scroll
});
onwheel
根據導航到錨點時您到底不想觸發滾動處理程序的原因,可以考慮僅將其附加到onwheel
事件上。 這意味着其他滾動方式(觸摸,錨點,箭頭鍵, Page Down等)不會觸發您的處理程序。
雖然不可能阻止實際事件的觸發(因為它是瀏覽器代碼的一部分,並且按設計的方式工作),但是除了$(window).scrollTop() > 0
(最初位於該位置),您還可以檢查窗口位置是否存在哈希,如果存在,則檢查滾動量是否與URL哈希所引用元素的垂直偏移量不同。
像這樣:
$(window).scroll(function(){
if($(window).scrollTop() > 0 && // if it's scrolled and
(!window.location.hash || // if there's no hash or
$(window.location.hash).offset() && // there is, but the scroll is elsewhere
$(window.location.hash).offset().top != $(window).scrollTop())
) {
alert('scroll'); // trigger the callback
}
});
實時代碼:
$(window).scroll(function(){ if($(window).scrollTop() > 0 && ($('#c:checked').length == 0 || (!window.location.hash || $(window.location.hash).offset() && $(window.location.hash).offset().top != $(window).scrollTop() ) ) ) { $('div').addClass('on'); setTimeout(function(){ $('div').removeClass('on'); }, 1000) } });
p {margin: 500px 0;} div {position: fixed; top: 0; right: 0; opacity: 0.1; transition: all .2s linear; padding: 4px 8px} div.on {opacity: 1; background: #cfc;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="c" type="checkbox" checked="checked">Prevent scroll callback on link clicks<br> <a href="#shomz">Link to the anchor below</a> <p id="shomz">Anchor here</p> <div>Scroll triggered</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.