开发者

Bind a key (for page transition with backspace) only if the key is NOT pressed in an input field?

开发者 https://www.devze.com 2023-01-16 15:12 出处:网络
i don\'t know why, but i got this already to work but today it stopped working. The base code is: $(document).bind(\"keydown\", function(e){

i don't know why, but i got this already to work but today it stopped working. The base code is:

$(document).bind("keydown", function(e){
    if (e.keyCode) code = e.keyCode;         // für alle Browser
    else if (e.which) code = e.which;         // für ie
    if(code==8) {
    $("#outer-frame").fadeOut(400, function (){ //content fade-out
        history.back(-1); //gehe einen Schritt in der Browser-History zurück
});
    return false; // Browser bricht ab
}
});

and i also had an if statement, don't know it anymore, it suddenly stopped working. I want that the backspace key is bind to keydown and execute a page transition effect. No problem as long is i want to prevent the whole thing beeing called if a user hits the backspace key in an input field, es he would be redirected to the last page in his history.

PLS help me! It's so annoying if something just stopped working.

I used the :focus selector from css like if ( $("input:focus") ...

Just want to add that the browser switch is not from me, the bind event and if(code==8) was my coding, fade and history also but nothing unique you'll find a lot of examples so i did during during my research about different browser behaviour (where i found some similiar code, but i think that's jQuery 开发者_开发百科... and jQuery is awesome!).

I'm so happy with the solutions provided by Ken Egozi and SimpleCoder and really want to thank both of you for your help!


You need to continue (return true) if he key pressed within a textarea, a textbox or a password box.

Add

if ($(e.target).is("textarea, input[type=text], input[type=password]")) return true;

to your handler, before the if (code==8) bit


I would do this:

$(document).bind("keydown", function(e) {
    if ((e.target.nodeName.toLowerCase() != "input" && e.target.nodeName.toLowerCase() != "textarea") && e.which == 8) {
        $("#outer-frame").fadeOut(400, function() {
            history.back(-1);
        });
        return false; // unterbricht die Verarbeitung durch den Browser
    }
});

Also, just so you know, jQuery automatically normalizes the e.which property so:

if (e.keyCode)
    code = e.keyCode; // für alle Browser
else if (e.which)
    code = e.which; // für ie
if (code == 8) {

can be written as

if (e.which == 8) {
0

精彩评论

暂无评论...
验证码 换一张
取 消