jQuery 水平滚动时如何防止浏览器在历史记录中后退/前进?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16182993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 16:38:05  来源:igfitidea点击:

How to prevent a browser from going back/forward in history when scrolling horizontally?

javascriptjqueryfirefoxbrowserwebkit

提问by Steve Chan

How can one disable a modern browsers default functionality using JQuery or Native JS for going backwards or forwards when scrolling horizontally?

如何使用 JQuery 或 Native JS 禁用现代浏览器的默认功能,以便在水平滚动时向后或向前?

This usually happens when using a trackpad and when scrolled to the end or start of a scrollable div.

这通常发生在使用触控板以及滚动到可滚动 div 的末尾或开头时。

采纳答案by Steve Chan

So I figured since i've created a web app, why not prompt the user for any unsaved changes which will defer the user from loosing any unsaved changes or ending up on the previous or next page in the browser history.

所以我想,既然我已经创建了一个网络应用程序,为什么不提示用户进行任何未保存的更改,这将推迟用户丢失任何未保存的更改或在浏览器历史记录中的上一页或下一页结束。

Here is the solution if any one else comes across this problem like I did:

如果其他人像我一样遇到这个问题,这里是解决方案:

window.onbeforeunload = function(e) {
    return 'Ask user a page leaving question here';
}; 

回答by u283863

history.pushState(null, null, location.href);
window.onpopstate = function(event) {
    history.go(1);
};

Demo: http://jsfiddle.net/DerekL/RgDBQ/show/

演示:http: //jsfiddle.net/DerekL/RgDBQ/show/

You won't be able to go back to the previous webpage, unless you spam the back button or hold down the back button and choose the previous entry.

您将无法返回上一个网页,除非您发送后退按钮或按住后退按钮并选择上一个条目。

Note: onpopstate(or event onbeforeunload) doesn't seem to work on iOS.

注意:(onpopstate或 event onbeforeunload)似乎不适用于 iOS。

回答by AndrewHipp

If you're on a mac this is caused by the Track Pad Gestures.

如果您使用的是 Mac,这是由 Track Pad Gestures 引起的。

System Preferences -> Trackpad -> More Gestures. 

Not the JS solution you're looking for, but if you just want to prevent it for yourself you can turn the feature off.

不是您正在寻找的 JS 解决方案,但如果您只想自己阻止它,您可以关闭该功能。

回答by avetisk

Works in Chrome and Safari (i.e tested with Chrome and Safari):

适用于 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);