[英]IE: Is there a fast way to get the caret position in an iframe on designMode?
[英]Get the parent element of caret position inside iframe (with designmode on) in IE
這是以下問題的后續問題: 如何使用Javascript在瀏覽器的可編輯內容窗口中的光標處找到DOM節點?
這是由Tim向下回答。
在IE的iframe內獲取插入符號位置的父元素(不選擇)時存在問題(在Firefox中,效果很好)。
這是該答案的部分代碼:
if (ob.document.selection && ob.document.selection.createRange) {
range = ob.document.selection.createRange();
alert(range.parentElement().innerHTML); //I get blank
return range.parentElement();
}
其中ob是:
document.getElementById('myIframe').contentWindow;
iframe的externalHtml(用於測試):
"<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>" +
"<html xmlns='http://www.w3.org/1999/xhtml'>" +
"<head>" +
"<title>testing</title>" +
"</head>" +
"<body><p>some text for testing<b>I am bold</b> more testing</p>"+
"<p>blablabla</p>" +
"<p>121213134</p></body>" +
"</html>");
因此,當您在任何單詞上插入插入符號時,結果都是“空白”。
我希望您解決的另一個問題:
如果您選擇“我是粗體”內的部分,則返回的父元素是“我是粗體”(b元素)。
是否可以返回P元素? (當然,它也適用於其他情況)
更新:
選擇功能的調用是通過位於托管iframe的文檔上的一個簡單按鈕臨時進行的:
<input type="button" value="test" onclick="getElementInRange()"/>
另外還有Init()函數,該函數在設置iframe的externalHTML的負載下運行(盡管我認為這不重要):
function Init() {
document.getElementById('myIframe').contentWindow.document.designMode = "on";
document.getElementById('myIframe').contentWindow.document.open("text/html", "replace");
document.getElementById('myIframe').contentWindow.document.write(//*Here comes the string from above...*
document.getElementById('myIframe').contentWindow.document.close();
}
更新2:
我嘗試添加到按鈕:unselectable =“ on”,這有時會導致奇怪的異常,即使插入符號位於相同的位置,有時它也會返回正確的值ans!
更新3
經過更多測試后,我發現“異常”發生在iframe失去焦點並且單擊(單擊后發生什么狀態,我沒有檢查)按鈕后iframe消失了(如果消失,結果為空白) ,如果保持不變,則結果符合預期)。
因此,問題是如何將插入符號保留在iframe中,這無關緊要?
因此,問題是如何將插入符號保留在iframe中,這無關緊要?
在按鈕上分配一個mousedown事件。 這將在從iframe刪除插入符號之前觸發。 但是它只能運行一次,因此將對對象的引用保存到變量中是一個好主意。
$("button").mousedown(function(){ parent = getSelectionContainerElement(); });
您確實應該嘗試使用Google Closure庫中的范圍類 。
goog.require('goog.dom.Range');
var range = goog.dom.Range.createFromWindow(ob);
return range.getStartNode().parentNode;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.