简体   繁体   中英

Alert box doesn't show even after return false

See code:

area.onkeydown = function(e){
    e = e || window.event;

    if(e.shiftKey && e.keyCode === 32){
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();

        // no alert here

        return false;
    }
};

Here, the code works, and on pressing Shift + Space , the space doesn't get inserted. However, as soon I insert an alert , it doesn't work, ie the space gets inserted and the alert box also doesn't show.

area.onkeydown = function(e){
    e = e || window.event;

    if(e.shiftKey && e.keyCode === 32){
        e.preventDefault();
        e.stopPropagation();
        e.stopImmediatePropagation();

        alert("typed"); // this alert doesn't show
        return false; // and space also gets insrted
    }
};

FIDDLE

What am I missing?

UPDATE:

  1. Using onkeyup would show the alert, but a space gets inserted.
  2. Using onkeypress would not insert the space, but the alert stays as long as the keys remain pressed.

So, I guess there is no way for me to get this working. And as Teemu puts it :

At your fiddle the snippet works with or without alert() without printing the space in IE11 (Win7). FF loses the preventDefault() behavior, though I can see the alert. In Chrome35 the alert only flashes on the screen and the space is printed. (If the flash is fast enough, your case?) IE uses an OS window to show an alert, other browsers have their own implementation, which seems to mess up the event handling.

UPDATE: I'm voting to close this question as off-topic because the problem can no longer be reproduced, the way it was described, in that fiddle in the latest Chrome version. Pressing Shift+Space now shows the alert box but does NOT insert any space.

i've change your keydown to keyup

See this

area.onkeyup = function(e){}

尝试使用onkeypress而不是onkeydown

Using Keyup instead of keydown reason is as below:

 area.onkeyup = function(e){

Demo

Keydown :

The keydown event is sent to an element when the user first presses a key on the keyboard . It can be attached to any element, but the event is only sent to the element that has the focus . Focusable elements can vary between browsers , but form elements can always get focus so are reasonable candidates for this event type.

Keyup :

The keyup event is sent to an element when the user releases a key on the keyboard . It can be attached to any element, but the event is only sent to the element that has the focus . Focusable elements can vary between browsers, but form elements can always get focus so are reasonable candidates for this event type.

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