2016-11-09 122 views
0

我如下得到一個iframe:的iFrame getFocus不會觸發

<iframe name="richTextField" id="richTextField" style="border:#000 1px solid; width:700px; height:300px;"></iframe> 

而且我有一些JavaScript的iframe中得到或失去焦點,應能觸發,但在Firefox它不工作,除非我在正手插入警報。腳本如下:

<script type="text/JavaScript"> 
    document.getElementById('richTextField').contentWindow.document.designMode="on"; 
    document.getElementById('richTextField').contentWindow.document.close(); 

    if(navigator.userAgent.indexOf("Firefox") != -1){ 
     //When alert below is removed, the blur/focus doesn't work in FireFox 
     alert("what?"); 
     $("#richTextField").contents().bind('blur', function(){ 
//   blur functions 
      console.log("Firefox Blur"); 
     }); 
     $("#richTextField").contents().bind('focus', function(){ 
//    focus functions 
      console.log("Firefox Focus"); 
     }); 
    } else { 
     $("#richTextField").contents().find("body").blur(function(){ 
//    blur functions 
      console.log("Blur"); 
     }); 
     $("#richTextField").contents().find("body").focus(function(){ 
//    focus functions 
      console.log("Focus"); 
     }); 
    } 
</script> 

回答

0

我犯了一個簡單的錯誤,在文檔準備好之前執行腳本。所以我不得不改變JavaScript的一點。所以我把上面的代碼放在下面的代碼中:

$(document).ready(function() { 
    //Above code without the script tags and without the alert 
});