简体   繁体   English

HTML节点位于contenteditable中的插入符位置<div>

[英]HTML node at caret position in contenteditable <div>

I am working on a basic Rich Text Editor (RTE) for a private site we're working on. 我正在为我们正在处理的私人站点开发基本的Rich Text Editor(RTE)。 The site requires the use of an RTE to add blog posts. 该网站要求使用RTE添加博客文章。

Everything is working fine, but I would like to toggle the active state of buttons in the toolbar when they have the specific style applied to them. 一切工作正常,但是当它们应用了特定样式时,我想切换工具栏中按钮的活动状态。 This works fine for things like bold, italic etc., since we can use document.queryCommandValue("Bold") , and so on. 因为我们可以使用document.queryCommandValue("Bold")等等,所以这对于诸如粗体,斜体等工作正常。

The problem we have is that there is no way to detect things such as <blockquote /> and <a /> tags. 我们遇到的问题是无法检测到<blockquote /><a />标记之类的东西。

We add <blockquote> elements to the RTE as follows: 我们将<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>');
    }
}

My question is, how can we detect the parent node at the caret position within a contenteditable <div> ? 我的问题是,如何才能在contenteditable <div>的插入符号位置检测父节点? For example, placing my cursor inside the <blockquote> node should return 'blockquote' (or something similar). 例如,将光标放在<blockquote>节点内应返回“ blockquote”(或类似内容)。

jQuery is an option. jQuery是一个选项。

So, given the following example: 因此,给出以下示例:

<blockquote>Some| <b>text</b></blockquote>
                ^ cursor/caret position

I am looking to return blockquote (because Some text is within a blockquote). 我希望返回blockquote (因为在blockquote中Some text )。

So here is way you can check if to see what sort of an element you are currently in. The function works with chrome. 因此,这是您可以检查是否查看当前所处元素类​​型的方法。该函数适用于chrome。 With the recursive function we are able to return the entire array. 使用递归函数,我们可以返回整个数组。

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;
}

A jsfiddle link can be found here : http://jsfiddle.net/s6xXH/3 可以在这里找到jsfiddle链接: http : //jsfiddle.net/s6xXH/3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM