[英]HTML node at caret position in contenteditable <div>
我正在為我們正在處理的私人站點開發基本的Rich Text Editor(RTE)。 該網站要求使用RTE添加博客文章。
一切工作正常,但是當它們應用了特定樣式時,我想切換工具欄中按鈕的活動狀態。 因為我們可以使用document.queryCommandValue("Bold")
等等,所以這對於諸如粗體,斜體等工作正常。
我們遇到的問題是無法檢測到<blockquote />
和<a />
標記之類的東西。
我們將<blockquote>
元素添加到RTE中,如下所示:
// Insert a blockquote:
this._blockquote = function()
{
// Get the selected text:
var theText = this._getSelectedText();
// Are we replacing?
if(theText != '')
{
var quote = $('<blockquote />').html(theText).html();
this._cmd('inserthtml', '<blockquote>'+quote+'</blockquote>');
}
else
{
this._cmd('inserthtml', '<blockquote></blockquote>');
}
}
我的問題是,如何才能在contenteditable
<div>
的插入符號位置檢測父節點? 例如,將光標放在<blockquote>
節點內應返回“ blockquote”(或類似內容)。
jQuery是一個選項。
因此,給出以下示例:
<blockquote>Some| <b>text</b></blockquote>
^ cursor/caret position
我希望返回blockquote
(因為在blockquote中Some text
)。
因此,這是您可以檢查是否查看當前所處元素類型的方法。該函數適用於chrome。 使用遞歸函數,我們可以返回整個數組。
function returnNodeType()
{
var node=null;
node=window.getSelection().getRangeAt(0).commonAncestorContainer;
node = ((node.nodeType===1)?node:node.parentNode);
var nodeArray = [];
returnarray = returnParentTag(node, nodeArray);
return returnarray;
}
function returnParentTag(elem, nodeArray) {
nodeArray.push(elem.tagName);
if(elem.id != "editor") {
var next = returnParentTag(elem.parentNode, nodeArray);
if(next) return next;
}
else
return nodeArray;
}
可以在這里找到jsfiddle鏈接: http : //jsfiddle.net/s6xXH/3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.