2012-10-04 48 views
0

我不太確定我做錯了什麼,我擡頭看看一個元素是否有焦點。我找到了document.hasFocus()方法。所以我試着在Chrome上進行調試,得到了「Uncaught TypeError:Object#has no method'hasFocus'。」。這裏是我的JavaScript:hasFocus()返回錯誤

var e = document.getElementById("editor").contentWindow; 
e.document.designMode="on"; 
e.document.open(); 
e.document.write("<head><style>body{font-family:arial,helvetica,sans-serif;font-size:12px;}</style></head>"); 
e.document.close(); 
function def() { 
    document.getElementById("fonts").selectedIndex = 0; 
    document.getElementById("size").selectedIndex = 1; 
    document.getElementById("color").selectedIndex = 0; 
} 
function edit(x, y) { 
    e.document.execCommand(x, false, y); 
    e.focus(); 
} 
setInterval(function() { 
    if (document.getElementById("editor").contentWindow.hasFocus()) { 
     document.getElementById("html").value = document.getElementById("editor").contentWindow.document.body.innerHTML; 
    } 
    else if (document.getElementById("html").hasFocus()) { 
     document.getElementById("editor").contentWindow.document.body.innerHTML = document.getElementById("html").value; 
    } 
}, 100); 

回答

1

方法「hasFocus」只存在於文檔對象上,而不存在於單獨的節點上。請參閱 - https://developer.mozilla.org/en-US/docs/DOM/document.hasFocus

如果要檢查輸入是否爲焦點,可以通過更新輸入的「onfocus」事件上的變量並檢查該焦點元素的變量來完成。請參閱 - In Javascript find if a checkbox is focused

+0

這將檢查iframe是否有焦點?因爲這是一個所見即所得的編輯器。 – Solo

+0

可能。取決於所見即所得編輯器的實現方式。嘗試一下。另請參閱 - http://www.sitepoint.com/forums/showthread.php?273772-How-to-detect-iframe-onfocus-event-in-Firefox和http://robsanheim.com/2006/05/ 23 /瀏覽器的漏洞-的onblur和-的onfocus與 - I幀/ – levi