Can I intercept control-A keypresses on IE?

吃可爱长大的小学妹 提交于 2019-12-08 09:35:29

问题


I'm trying to use jQuery to intercept control-A keypresses on my web page, like so:

$(document).keypress(function (event) {
    if (event.ctrlKey && (event.which == 65 || event.which == 97)) {
        event.preventDefault();
        // ...
    }
});

This works on Firefox, but on IE7, my event handler doesn't get called, and all of the text on the page gets selected instead (as happens on Firefox without the event handler).

Is there any way I can intercept control-A's on IE?


回答1:


This works under FF 3.5 and IE7 for me:

    $(function() {
        var isCtrl = false; 

        $(document).keyup(function (e) { 
            if(e.keyCode == 17)
                isCtrl = false;
        }).keydown(function (e) { 
            if(e.keyCode == 17)
                isCtrl = true;

            if(e.keyCode == 65 && isCtrl == true) {
                alert('Intercepted CTRL+A');
                e.preventDefault();
            }
        }); 
    });



回答2:


If you do a return false in the event handler then it will cancel the browsers behavior. Depending on the browser it can behave differently (for instance keypress will still fire on firefox after a keydown has canceled it, while IE will stop it).



来源:https://stackoverflow.com/questions/1652210/can-i-intercept-control-a-keypresses-on-ie

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!