2017-01-15 24 views
1

基本上我有一個HTML 5的視頻元素,點擊時我需要使它聚焦,這樣我才能控制用戶鍵盤觸發器。如何設置專注於點擊的元素?

這裏是我的代碼:

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

除了我的視頻元素我有一個文本框。問題是,當影片播放中心的IT禁止我在我的文本框中鍵入並保持觸發鍵按鈕用於視頻處理即使我:

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

問候:)

+0

'$(window).click'中的'e'沒有被定義。所以回調最有可能在點擊時引發錯誤,即使不是'e'不會是點擊事件。 –

+0

@ t.niese仍然不起作用 – user3596474

回答

0

不要使用event.srcElement這是Firefox不支持的非標準IE屬性。使用所有現代瀏覽器支持的event.target。嘗試使用.blur()方法將focus遠離視頻。例如,請參閱代碼片段,瞭解如何完成此操作。

代碼片段

$(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>

+0

那麼這與元素焦點工作,但它仍然觸發按鈕作爲視頻處理程序。 – user3596474

+0

我忘了刪除'tabindex'屬性。如果刪除它們並不能解決這個問題,你可以發佈「結束」事件的事件處理程序嗎?有可能你忽略了一些東西,而一組新鮮的眼睛(我實際上是充血的)可能會找到一些東西。 – zer00ne

0

它可以幫助別人了。

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; 
} 

,稍後我們可以打電話notfocused方法來刪除處理鍵盤按鍵的視頻。

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