如何防止Backspace在javascript中导航? [英] How can I prevent Backspace from navigating back in javascript?

查看:62
本文介绍了如何防止Backspace在javascript中导航?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这适用于IE,但我无法在Opera或Firefox中使用它。当且仅当当前焦点是SELECT下拉列表时,我想阻止Backspace导航。

This works in IE, but I cannot get it to work in Opera or Firefox. I want to prevent Backspace from navigating away if and only if the current focus is the SELECT dropdown.

<html>
<body>
<select id="testselect">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>
<script language="javascript">
    document.getElementById("testselect").onkeydown = function(e) {
        if(!e) {
            e = event;
        }
        alert(e.keyCode);
        if (e.keyCode == 8 || e.keyCode == 46) {
       e.returnValue = false;

        e.cancelBubble = true;
        if (e.stopPropagation) { e.stopPropagation(); alert("stoppropagation");}
        if (e.preventDefault) { e.preventDefault(); alert("preventdefault");}
        return false;
        }
    };
</script>
</body>
</html>


推荐答案

嗯,事实证明Opera需要事件是在 onkeypress 事件中取消,而不是onkeydown。

Well, turns out that Opera needs the event to be cancelled in the onkeypress event, not onkeydown.

参考: http://jimblackler.net/blog/?p=20

这篇关于如何防止Backspace在javascript中导航?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆