简体   繁体   中英

event.preventDefault behaving weirdly in Firefox on keydown

The code below is effective in preventing the browser default from firing in Chrome and Safari. For some reason, however, my code does not fire even after pressing the arrow key in Firefox.

$(window).keydown(function(e) {
    switch(e.which){
        case 39: //right arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow + z(10));
            break;
        case 37: // left arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow - z(10));
            break;
    }
});

I tried return false; instead of e.preventDefault(); too, but to no effect. I also tried putting e.preventDefault(); after the scrollLeft line, but it isn't working either. Any ideas?

try this -

code = e.keyCode || e.which;
switch(code){

Try this:

$(window).keydown(function(e) {
    switch(e.keyCode){
        case 39: //right arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow + z(10));
            break;
        case 37: // left arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow - z(10));
            break;
    }
});

I just came across this issue, myself. I added an event listener for a select input's keydown event to disable left/right keys from traversing the options top/right, respectively. It works perfectly in Chrome and IE. Based on what I've read, so far, it definitely is a bug that has had a lot of debate and speculation on whether or not to actually treat it as a bug. I even went as far as to attach another event listener to the aforementioned select input for keyup; which I noticed was triggering, too, after invoking preventDefault from within the keydown event (Firefox). However, the action is not prevented. Pretty annoying.

Still trying to determine a workaround.

Try this,

Updated

$(window).keydown(function(e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    switch(code){
        case 39: //right arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow + z(10));
            break;
        case 37: // left arrow key
            e.preventDefault();
            $('body').scrollLeft(scrollNow - z(10));
            break;
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM