开发者

js deactivate spacebar when typing in textfield

I am creating a music player which uses the spacebar to pause and play audio, now is it possible to know if someone is currently typing in a textfield, because right now, if this user types in a textfield and audio is playing, when the user presses space the audio pauses, I would like basically that when the user is not in a textfield that a user can just play and pause audio, but when the user is typing that this function is disabled so the audio keeps playing. The code below, is the code I'm am current using for detecting when space is pressed;

//IF Space bar is Pressed
$(window).keypress(function(e) {
if(e.keyCode == 32) {
    if(document.getElementById('audio').paused){
        if(document.getElementById('video').style.display=="block"){

        }
        else{
            document.getElementById('audio').play();
            document.getElementById('pause开发者_JAVA技巧').style.display="block"; 
            document.getElementById('play').style.display="none";
        }
    }
    else{
        if(document.getElementById('video').style.display=="block"){

        }
        else{
            document.getElementById('audio').pause();
            document.getElementById('pause').style.display="none";
            document.getElementById('play').style.display="block";
        }
    }
}
});
//END IF Space bar is pressed


Check the event sources tagName attribute:

function(e) {
 e = e || event;
 var el = e.srcElement || e.target,
     cando = !(/textarea|input/i.test(el.tagName));

 if(cando && e.keyCode == 32)  {
   /etc.
 }
}


You could also try

if(e.keyCode == 32 && document.activeElement != document.getElementById('someTextBox'))

New code

//IF Space bar is Pressed
$(window).keypress(function(e) {
if(e.keyCode == 32) {
    var inputs = document.getElementsByTagName('input');

    for(var item in inputs)
    {
        if(inputs[item] == document.activeElement)
            return;
    }

    if(document.getElementById('audio').paused){
        if(document.getElementById('video').style.display=="block"){

        }
        else{
            document.getElementById('audio').play();
            document.getElementById('pause').style.display="block"; 
            document.getElementById('play').style.display="none";
        }
    }
    else{
        if(document.getElementById('video').style.display=="block"){

        }
        else{
            document.getElementById('audio').pause();
            document.getElementById('pause').style.display="none";
            document.getElementById('play').style.display="block";
        }
    }
}
});
//END IF Space bar is pressed


Check if a textarea has focus

if(e.keyCode == 32 && !text_area_has_focus) { ... 

Logic for that could be something like this, if you're willing to use jQuery:

if(e.keyCode == 32 && !$('input[type=text]:focus').length) { ... 
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜