简体   繁体   中英

How to set an element focused on click?

Basically I've a HTML 5 video element which on click I need to make it to be focused so I could control user keyboard triggers.

Here is my code:

$(function(){
    var focused_vid;
    $('.videoe').click(function(){ focused_vid = this });
    $(document).keydown(function(e){ 
        if (focused_vid){
            // keyboard handler
        }
    });
});

Beside my video element I've a Text Box. The problem is once the video is focused It disable me to type on my Text Box and keeps triggering Key button for video handler even though I've:

$(window).click(function(e) {
    $(e.srcElement.className).focus();
});

Regards :)

Do not use event.srcElement it's a non-standard IE property that Firefox doesn't support. Use event.target which is supported by all modern browsers. Try the .blur() method to take the focus away from the video. See the Snippet for example of how this could be done.

SNIPPET

 $(function() { var focused_vid; $('#vid1').click(function() { focused_vid = this }); $(document).keydown(function(e) { if (focused_vid) { console.log('focused on ' + e.target.className); } }); }); $(window).click(function(e) { $('#vid1').blur(); var tgt = e.target; $(tgt).focus(); console.log('focused on ' + tgt.className); }); 
 /* This just to prevent the console from obscuring the demo */ input { display: block; } .as-console-wrapper.as-console-wrapper { margin-left:270px; max-width: 250px; height: 100vh; color: blue; font: 400 15px/1.3 Consolas; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id='inp1' class='txt' tabindex='2' placeholder="Enter this video's title"> <video id="vid1" class='vid' src="http://html5demos.com/assets/dizzy.mp4" controls tabindex='1' width='250'></video> 

It might help others too.

var focused_vid=null;
$(function(){
    $('.videoe').click(function(){ focused_vid = this });
    $(document).keydown(function(e){ 
        if (focused_vid){
            // keyboard handler
        }
    });
});

function notfocused(){
    focused_vid=null;
}

And later on we Can call notfocused method to remove handling keyboard buttons for video.

$(document).click(function(e) {
    $('.videoe').blur();
    var tgt = e.target;
    $(tgt).focus();
    if(tgt.className!="videoe")
        notfocused();
});

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