javascript - 如何防止 Backspace 在 javascript 中导航回来?

标签 javascript

这在 IE 中有效,但我无法在 Opera 或 Firefox 中使用。当且仅当当前焦点是 SELECT 下拉菜单时,我想阻止退格键离开。

<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>

最佳答案

使用 jquery - 仅用于选择下拉菜单

$(document).ready(function(){ 
     //for IE use keydown, for Mozilla keypress  
     //as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
     $('select').keypress(function(event){if (event.keyCode == 8) {return false;}});
     $('select').keydown(function(event){if (event.keyCode == 8) {return false;}});
}

对于页面中除输入控件和textarea之外的所有元素如下

<script type="text/javascript">

    //set this variable according to the need within the page
    var BACKSPACE_NAV_DISABLED = true;

    function fnPreventBackspace(event){if (BACKSPACE_NAV_DISABLED && event.keyCode == 8) {return false;}}
    function fnPreventBackspacePropagation(event){if(BACKSPACE_NAV_DISABLED && event.keyCode == 8){event.stopPropagation();}return true;}

    $(document).ready(function(){ 
        if(BACKSPACE_NAV_DISABLED){
            //for IE use keydown, for Mozilla keypress  
            //as described in scr: http://www.codeproject.com/KB/scripting/PreventDropdownBackSpace.aspx
            $(document).keypress(fnPreventBackspace);
            $(document).keydown(fnPreventBackspace);

            //Allow Backspace is the following controls
            $('input').keypress(fnPreventBackspacePropagation);
            $('input').keydown(fnPreventBackspacePropagation);
            $('textarea').keypress(fnPreventBackspacePropagation);
            $('textarea').keydown(fnPreventBackspacePropagation);
        }
    }); 

</script>

关于javascript - 如何防止 Backspace 在 javascript 中导航回来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1773178/

相关文章:

javascript - Angular-UI Datepicker 最小日期设置与另一个日期

javascript - 使用类型按钮 javascript 提交表单

JavaScript 不会在函数中输出值

javascript - 替换 true 时合并 ngClass 属性

javascript - 为什么 Chrome 控制台中的 {} + {} 不再是 NaN?

javascript - onMouseOver 事件在 React 中不起作用

javascript - 拖拽 : Can't move to left and top

javascript - 使用 JavaScript 中的 Reduce 方法取平均值

javascript - 使用 jquery 数据表插件将选择菜单添加到多个表

javascript - 带有隐藏字段的表单提交