简体   繁体   中英

Javascript keypress

Try to do something hide alert window by pressing spacebar or any key in keyboard.

existing only able to do using click listener.

$('.alertWindow1').click(function (event) {
    s.hide();
});

Trying this code but not able function

$('.alertWindow1').keypress(function (event) {
    if (event.keyCode == 27) {
         s.hide();
    }
});

This is full existing code, try to add hide the alert window using keypress

<script type="text/javascript">
    jQuery.extend({
        alertWindow: function (e, n) {
            var e = e, r; n === undefined ? r = "#00a8b7" : r = n;
            if ($("body").find(".alertWindow1").length === 0) {
                var i = '<div class="alertWindow1" style="width: 100%;height: 100%; background:rgba(0,0,0,0.5);position: fixed; left:0px; top: 0px; z-index: 9999;"><div id="successImg" style="margin-top:200px;margin-left:20px;text-             align:center;" >' + "</div>" + "</div>";
                $("body").append(i);
                var s = $(".alertWindow1");
                var ddbarcode = $('#hidbarcode').val();
                if (ddbarcode != "") {
                    displayCard(ddbarcode);
                    
                }
                $('.alertWindow1').click(function (event) {
                    s.hide();
                });
            }
            else {
                $(".alertWindowContent").text(e), $(".alertWindow1").show(), setTimeout(function () {
                    $(".alertWindow1").hide();
                }, 1000);
            }
        }
    })

</script>

You need to think about where the event is firing, and where it will bubble to.

Key events start wherever the focus is.

The div you are adding to the document isn't focusable. It has no descendants that are focusable. Even if it did, you haven't done anything to move the focus from where it is now to such an element.

So the key event will start where the focus is now and bubble up until it hits the document object without even passing through that div . This means it never passes anywhere that you listen for it.

You can listen on the document object instead.

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