Using event.which to verify if the user pressed the spacebar doesn't work in Firefox

后端 未结 4 604
粉色の甜心
粉色の甜心 2021-01-06 07:59

I want a script to verify if the key pressed is \'spacebar\', keycode 32. I noticed that IE uses other function names.

I tried a lot of solutions found here and this

4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-06 08:09

    I've never had any problems with the following and I've used it in IE6 through IE9, Firefox 3.5-5 and Chrome from at least 9-13

    function captureSpace (evt) {
        var e = evt || event;
        var code = e.keyCode || e.which;
        if (code === 32) {
            // Do your thing...
        }
    }
    

    This uses a logical OR to basically say if evt is a falsy value then use the window.event

    var e = evt || event;
    

    This uses a logical OR to assign the code for the key pressed in the same way

    var code = e.keyCode || e.which;
    

    This gives you a true or false value if the code is exactly equal to the integer value of 32

    (code === 32)
    

    I also suggest that you assign this to the key UP event.

提交回复
热议问题