如何将所选元素置于一个可信的元素中 [英] How to get the selected element inside a contenteditable element

查看:88
本文介绍了如何将所选元素置于一个可信的元素中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我检查了这个问题,以及这个,问题是它给了我当前选择的内容,但我想要取而代之的是dom元素。

I checked out this question, and this one, the problem is it gives me the content of the current selection, but I want the dom element instead.

我正在寻找一种方法来获取当前正在使用javascript编辑的元素的标记名。例如:

I'm looking for a way to get the tagname of an element that is currently being edited with javascript. For example:

<article contenteditable=true>
    <h2>Some List</h2>
    <ul>
        <li>Item 1</li>
        <li>Item *caret here* 2</li>
        <li>Item 3</li>
    </ul>
</article>

我希望能够将列表项放入javascript el 变量。所以我可以这样做:

I want to be able to put the list item into a javascript el variable. So I that I can do for example:

el.tagName
el.className






有谁知道如何实现这一目标? Tx:)


Does anyone know how to achieve this? Tx :)

推荐答案

您可以使用范围指代文档的选定部分,而不是检查< ul> 的US / docs / Web / API / Range / commonAncestorContainerrel =noreferrer> commonAncestorContainer

在您的示例中,如果您选择列表的一部分,则可以使用以下内容检索< ul>

You can use a Range to refer to the selected part of the document and than check the commonAncestorContainer for retriving the <ul>.
In your example if you select part of the list you can retrieve the <ul> with something like:

    var sel = window.getSelection();
    var range = sel.getRangeAt(0);
    var ulTag = range.commonAncestorContainer;

如果您想要获取光标指向的元素(没有选择),您可以请参阅 startContainer 属性,然后查看 parentNode 用于重新获取< li> 。例如:

If you instead want to get the element pointed by the cursor (without there being a selection) you can refer to the startContainer property and than check the parentNode for retriving the <li>. For example:

    var sel = window.getSelection();
    var range = sel.getRangeAt(0);
    var pointedLiTag = range.startContainer.parentNode;

请注意,这些只是简单的用例,在真实文档中有很多嵌套元素,因此您必须确保在使用之前检索的元素是您所期望的元素。

这篇关于如何将所选元素置于一个可信的元素中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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