[英]How to prevent a browser from going back/forward in history when scrolling horizontally?
如何在水平滾動時使用 JQuery 或 Native JS 禁用現代瀏覽器的默認功能以向后或向前?
這通常發生在使用觸控板以及滾動到可滾動 div 的末尾或開頭時。
history.pushState(null, null, location.href);
window.onpopstate = function(event) {
history.go(1);
};
演示: http : //jsfiddle.net/DerekL/RgDBQ/show/
您將無法返回上一個網頁,除非您發送后退按鈕或按住后退按鈕並選擇上一個條目。
注意: onpopstate
(或事件onbeforeunload
)似乎不適用於 iOS。
所以我想既然我已經創建了一個網絡應用程序,為什么不提示用戶進行任何未保存的更改,這將推遲用戶丟失任何未保存的更改或在瀏覽器歷史記錄中的上一頁或下一頁結束。
如果其他人像我一樣遇到這個問題,這里是解決方案:
window.onbeforeunload = function(e) {
return 'Ask user a page leaving question here';
};
如果您使用的是 Mac,這是由 Track Pad Gestures 引起的。
System Preferences -> Trackpad -> More Gestures.
不是您正在尋找的 JS 解決方案,但如果您只想自己阻止它,您可以關閉該功能。
適用於 Chrome 和 Safari(即使用 Chrome 和 Safari 測試):
// el === element on which horizontal scrolling is done
// (can be container of scrolled element or body or any other ancestor)
var preventHistoryBack = function (e) {
var delta = e.deltaX || e.wheelDeltaX;
if (! delta) {
return;
}
window.WebKitMediaKeyError /*detect safari*/ && (delta *= -1);
if (((el.scrollLeft + el.offsetWidth) === el.scrollWidth && delta > 0) || (el.scrollLeft === 0 && delta < 0) ) {
e.preventDefault();
}
};
el.addEventListener('mousewheel', preventHistoryBack);
以下是使用 CSS 的overscroll-behaviour 屬性可能對您有用的東西:
document.body.style.overscrollBehaviour = "contain";
body {
overscroll-behaviour: contain;
}
在撰寫本文時,即 2020 年 7 月 10 日,這會導致在頁面左端向左滾動不再觸發向后歷史導航。
我不確定這會對其他用戶體驗產生什么其他副作用。 我希望這可以應用於元素內部,但似乎這僅在應用於文檔正文時才有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.