如何禁用浏览器的默认帮助功能

时间:2012-01-26 14:07:16

标签: javascript jquery javascript-events cross-browser

我想禁用或覆盖浏览器的默认帮助功能。

我试着在网上看几个例子,但它们并不适合我。 (以下代码适用于ff和chrome,但不适用于opera& ie)

<html>
<title>
</title>
<body>
    <script src = "jquery-1.7.1.min.js" text="type="text/javascript""></script>
    <script language="javascript" type="text/javascript">           
            document.onkeydown = function(event)
            {
                if(window.event && window.event.keyCode == 112)
                {
                     event.stopPropagation();
                     event.preventDefault();
                     event.keyCode = 0;
                     return false;
                    //document.onhelp = new Function("return false;");
                    //window.onhelp = new Function("return false;");
                    //helpFunction();

                }
                else if(event.which == 112)
                {
                    helpFunction();
                }
            };
            var false_function = new function(){"return false";};
            shortcut.add("f1",false_function);
        var helpFunction = function() {
            alert('help');
        }
    </script>
    <h2>Test</h2>
</body>

1 个答案:

答案 0 :(得分:10)

我发现here此代码声称可用于每个版本的IE和FF

<script type="text/javascript">

function avoidInvalidKeyStorkes(evtArg) {
    var evt = (document.all ? window.event : evtArg);
    var isIE = (document.all ? true : false);
    var KEYCODE = (document.all ? window.event.keyCode : evtArg.which);

    var element = (document.all ? window.event.srcElement : evtArg.target);
    var msg = "We have disabled this key: " + KEYCODE;

    if (KEYCODE == "112") {
        if (isIE) {
            document.onhelp = function() {
                return (false);
            };
            window.onhelp = function() {
                return (false);
            };
        }
        evt.returnValue = false;
        evt.keyCode = 0;
        window.status = msg;
        evt.preventDefault();
        evt.stopPropagation();
        alert(msg);
    }

    window.status = "Done";    
}    

if (window.document.addEventListener) {
    window.document.addEventListener("keydown", avoidInvalidKeyStorkes, false);
} else {
    window.document.attachEvent("onkeydown", avoidInvalidKeyStorkes);
    document.captureEvents(Event.KEYDOWN);
}

</script>

工作JSFiddle。请注意,您必须在点击结果标签后对其进行测试。