如何获取正在编辑的元素? [英] How do I get the element being edited?

查看:70
本文介绍了如何获取正在编辑的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个webapp,我遇到了JavaScript问题。

I'm developing a webapp, and I have a problem with the JavaScript.

以下是导致问题的HTML的简化版本。我有一些嵌套 contenteditable divs (我用占位符文本替换了真实内容):

The following is a simplified version of the HTML causing the problem. I have some nested contenteditable divs (I replaced the real content with placeholder text):

<div contenteditable="true" id="div1">
    text
    <div contenteditable="inherit" id="div2">
        text
        <div contenteditable="inherit" id="div3">
            text
        </div>
        text
    </div>
    text
</div>

我想通过JavaScript获取所选元素(由用户编辑), 但到目前为止我还没有找到办法(成功)。

I want to get the element that's selected (being edited by the user) via JavaScript, but so far I haven't found a way to do it (successfully).

我尝试了什么以及为什么它不起作用

我尝试过使用 document.activeElement ,应该返回焦点中的任何元素。通常这可行,但在使用嵌套的 contenteditable 元素时,它不会产生所需的结果。它返回最上面的 contenteditable 祖先。而不是返回用户正在编辑的元素。

I have tried using document.activeElement, which is supposed to return whichever element is in focus. Normally this works, but it doesn't produce the desired result when working with nested contenteditable elements. Instead of returning the element that's being edited by the user, it returns the uppermost contenteditable ancestor.

例如,如果选择/正在编辑 div2 document.activeElement 将返回 div1 。如果选择/正在编辑 div3 document.activeElement 也会返回 div1

For instance, if div2 is selected/being edited, document.activeElement returns div1. If div3 was selected/being edited, document.activeElement also returns div1.

所以我猜 document.activeElement 不是正确的方法。

So I guess document.activeElement is not the right way to go about this.

如何获取正在编辑的最具体的元素,而不是最上面的 contenteditable ancestor?

How do I get the most specific element that's being edited, not its uppermost contenteditable ancestor?

推荐答案

我是通过插入一个在插入符号位置的虚拟元素并找到它的直接父元素。

I did it by inserting a dummy element at the caret position and finding it's direct parent.

function getActiveDiv() {
    var sel = window.getSelection();
    var range = sel.getRangeAt(0);
    var node = document.createElement('span');
    range.insertNode(node);
    range = range.cloneRange();
    range.selectNodeContents(node);
    range.collapse(false);
    sel.removeAllRanges();
    sel.addRange(range);
    var activeDiv = node.parentNode;
    node.parentNode.removeChild(node);
    return activeDiv;
}

我在小提琴上做了一个例子:
https://jsfiddle.net/shhe05cj/4/

I did an example on fiddle: https://jsfiddle.net/shhe05cj/4/

我在每个绑定到相关div的按键事件上运行它。

I run it on every keypress event that's bind to the relevant divs.

我将它基于另一个执行类似操作的线程:在contentEditable div中插入元素后立即设置插入位置

I based it on another thread that did something similar:Set caret position right after the inserted element in a contentEditable div

这篇关于如何获取正在编辑的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆