2015-01-05 45 views
2

我在頁面中有一些控件(控件保存在iframe中)。我正在keydown事件結合到下面的控件,無法將keydown事件綁定到整個文檔

$(function() { 
     $(document).on("keydown", function (e) { 
      if (e.altKey && e.keyCode === 74) { // j- key code. 
       $("#accordion").focus(); 
      } 
     }); 
    }); 

頁面加載後,如果我按Alt + J控制得到適當的鍍鉻而不是集中在Firefox和IE。只有當我點擊iframe區域然後按下alt + J時,控件纔會得到重點關注。如果我刪除了iframe,則控件將在所有瀏覽器中正確聚焦,而無需單擊iframe區域。如果我按下alt + J並且無需點擊iframe區域,如何讓控件獲得焦點?

在此先感謝。

+0

可能的重複http://stackoverflow.com/questions/5102214/document-keydown-not-working – miestasmia

回答

0

您可以在iframe中使用​​事件,並與.contents()這樣得到的內容:

您可以替換該行:此代碼

$("#accordion").focus(); 

$('iframe').contents().load(function(){ 
    $(this).find("#accordion").focus(); 
}); 

如果您正在使用iframe,那麼你必須等待iframe被加載,然後執行.focus()

2

我想你既可以使用的document.ready或在window.onload

例如請看下面:

$(document).ready(function() { 
     $(document).on("keydown", function (e) { 
     if (e.altKey && e.keyCode === 74) { // j- key code. 
      $("#accordion").focus(); 
     } 
    }); 
}); 

或者

$(window).load(function() { 
    $(document).on("keydown", function (e) { 
     if (e.altKey && e.keyCode === 74) { // j- key code. 
      $("#accordion").focus(); 
     } 
    }); 
}); 

我希望它能適用於所有

+0

OP已經在使用ready處理器... –

相關問題