使用 jQuery 在多个浏览器上停止退格键

发布于 2024-08-25 05:08:35 字数 951 浏览 6 评论 0原文

我试图阻止浏览器处理退格 keydown 事件,我正在使用 jQuery 库,所以我需要获取原始事件,但在某些浏览器上(至少是 Firefox)我得到尝试设置原始事件 keyCode = 0 时出现错误,它给出错误消息,指出该属性仅存在 getter。

function blockBackspace(event) {
    var altKey = event.originalEvent.altKey;
    var srcElementType = event.originalEvent.srcElement;
    if( (altKey) || ((event.keyCode == 8)  && (srcElementType != "text" && srcElementType != "textarea" && srcElementType != "password"))
        || ((event.ctrlKey) && ((event.keyCode == 78) || (event.keyCode == 82)) ) || (event.keyCode == 116) )
        {
        event.keyCode = 0;
        event.returnValue = false;
        event.originalEvent.keyCode = 0;
        event.originalEvent.returnValue = false;
        //sets process backspaceFlag to keep multiple handlers from removing text
        processBackspace = true;
    }
}

所以我不太确定下一步该做什么,我找到的每个解决方案都会产生更多问题。必须有解决这个问题的方法,否则其他文本区域(这就是我正在构建的)将无法工作。

I am attempting to stop a backspace keydown event from being handled by browsers, I'm using the jQuery library, so I need to get the original event, but on some browsers (Firefox at least) I get an error when trying to set the original events keyCode = 0, it gives and error saying that only a getter exists for that property.

function blockBackspace(event) {
    var altKey = event.originalEvent.altKey;
    var srcElementType = event.originalEvent.srcElement;
    if( (altKey) || ((event.keyCode == 8)  && (srcElementType != "text" && srcElementType != "textarea" && srcElementType != "password"))
        || ((event.ctrlKey) && ((event.keyCode == 78) || (event.keyCode == 82)) ) || (event.keyCode == 116) )
        {
        event.keyCode = 0;
        event.returnValue = false;
        event.originalEvent.keyCode = 0;
        event.originalEvent.returnValue = false;
        //sets process backspaceFlag to keep multiple handlers from removing text
        processBackspace = true;
    }
}

So I'm not exactly sure what to do next, every solution I find yields more problems. There must be ways around this problem or else other text areas (that's kind of what I'm building) would not work.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

戏剧牡丹亭 2024-09-01 05:08:35

你无法阻止事件的发生。一种替代方法是使用 beforeunload 专有事件,询问用户是否确实想要退出页面。

$(window).bind('beforeunload', function() {
    return "You want to leave the best page in the universe?";
});​

You can't stop the event from happening. One alternative is to use the beforeunload proprietary event that asks the user if they really want to exit the page.

$(window).bind('beforeunload', function() {
    return "You want to leave the best page in the universe?";
});​
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文