How to detect that Ctrl+R was pressed?

2019-01-17 10:50发布

I'm coding a function in jquery that executes if Ctrl+R is pressed but I can't seem to find out what the left and right ctrl keycodes are... Can someone please help?

UPDATE

    ///this works
    $(document).keydown(function(e){
      if(e.keyCode==17){alert("control was pressed")};
 });

Next Question-- How do I link control key press and another key press to execute a function?

  if(e.keyCode==17){llCtrlPress=1};
   if(e.keyCode==97 && llCtrlPress=1){DO SOMETHING}
  ????????????

That seems like it would work fine but then how do I set llCtrlpress back to '0' on keyup?

8条回答
做自己的国王
2楼-- · 2019-01-17 11:23

why aren't you using e.ctrlKey ?

 if (e.keyCode == 65 && e.ctrlKey) {
     alert('ctrl A');
 }

edit: here's an appropriate function to detect your ctrl-r keypress and stop the browser from reloading.

function keydown(e) {
    if (e.ctrlKey && e.keyCode == 82) {
        // 82 = r

        // TODO: your thing.

        if (e.preventDefault) {
            e.preventDefault();
        }
        else {
            return false;
        }
    }
}

i'm a jquery newbie, i think you'd do

$(document).keydown(keydown);

right?

查看更多
淡お忘
3楼-- · 2019-01-17 11:26

This is the code I'm using to disable refresh on IE and firefox (This works well for F5, Ctrl+F5 and Ctrl+R)

<script language="javascript" type="text/javascript">
    //this code handles the F5/Ctrl+F5/Ctrl+R
    document.onkeydown = checkKeycode
    function checkKeycode(e) {
        var keycode;
        if (window.event)
            keycode = window.event.keyCode;
        else if (e)
            keycode = e.which;

        // Mozilla firefox
        if ($.browser.mozilla) {
            if (keycode == 116 ||(e.ctrlKey && keycode == 82)) {
                if (e.preventDefault)
                {
                    e.preventDefault();
                    e.stopPropagation();
                }
            }
        } 
        // IE
        else if ($.browser.msie) {
            if (keycode == 116 || (window.event.ctrlKey && keycode == 82)) {
                window.event.returnValue = false;
                window.event.keyCode = 0;
                window.status = "Refresh is disabled";
            }
        }
    }
</script>

If you don't want to use useragent to detect what type of browser it is ($.browser uses navigator.userAgent to determine the platform), you can use

if('MozBoxSizing' in document.documentElement.style) - returns true for firefox

查看更多
登录 后发表回答