【问题标题】:How to find the top parent element of a text selection?如何找到文本选择的顶部父元素?
【发布时间】:2017-01-21 08:00:07
【问题描述】:

我有很多内容可编辑的 div。

当我通过在 contenteditable div 中突出显示来选择文本时,我想检索 contenteditable div 元素。

例如:

<div contenteditable="true">

Hello World, 

<i>this is <b>a dog</b> in the garden</i>

Thank you very much

</div>

所以当我通过突出显示选择文本“dog”时,我想检索 contenteditable div 元素,以便知道我使用了哪个 contenteditable div。

一个想法?

编辑:

我编写了这段代码,但它并不完美:

var selection = window.getSelection();

    var node = selection.anchorNode;

    for(var i = 0; i < 50; i++)
    {
        node = node.parentNode;

        if(node.getAttribute("contenteditable") == "true")
        {
            console.log("found");
            break;  
        }
    }

【问题讨论】:

    标签: javascript selection


    【解决方案1】:

    您需要在文本突出显示后触发一个事件。不幸的是,没有onhighlight 事件,所以你必须使用类似onmouseup 的东西。

    接下来,您需要一种将事件侦听器添加到所有contenteditable div 的方法。使用它的一种方法是document.querySelectorAll()。但是您可能会发现将一个事件侦听器添加到这些 divs 的“父级”并继续按照以下说明进行操作会更容易。

    mouseup 的事件监听器将提供一个事件对象。见https://developer.mozilla.org/en-US/docs/Web/Events/mouseup。该对象的值为currentTarget,它将为您提供发生mouseup 事件的元素,而该元素又是发生突出显示的元素。

    【讨论】:

      【解决方案2】:

      【讨论】:

        【解决方案3】:

        我认为以前的答案过于复杂。

        无论您选择文本还是仅单击一个元素,这都是一样的。

        您需要能够识别您已单击或按下某个键的当前元素(否则我看不出如何使 contenteditable 工作变得明智)。

        假设你可以做到这一点,你需要做的就是从 CurrentElm 返回到具有 contenteditable 属性和 while 循环的父级 -

        while (Elm.contenteditable != true) {Elm=Elm.parent}
        

        我承认没有提供完整的编程细节,但如果您需要,我可以提供。

        第一个问题是能够识别 mouseclickkeypress 上的 CurrentElm。

        如果你不能做到这一点,请回复我,我会解释 - 剩下的就变得容易了。

        【讨论】:

        • 哎呀 - 对不起 - 我的意思是 {Elm=Elm.parentNode} 是上面的。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-28
        • 1970-01-01
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-10
        相关资源
        最近更新 更多