我如何知道在contentEditable情况下哪个元素正在修改? [英] How do I know which element is modifying in contentEditable case?

查看:123
本文介绍了我如何知道在contentEditable情况下哪个元素正在修改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题。我在所见即所得的小编辑器上工作。我使用了带有选项contentEditable = true的div,我想知道何时单击按钮时用户正在修改div中的哪个元素。

I have a little problem / question. I work on a little WYSIWYG editor. I use a div with the option contentEditable="true" and I would like to know when there is a click on a button which element in my div is modifying by the user.

例如,如果div上有3个段落,并且该用户修改了第二个段落,我想知道当他单击按钮时,他当前正在修改第二个段落以显示文本内容!在此示例中, P2:

For example if there is 3 paragraphs on the the div, and that user modifies the second, I would like to know when he clicks on a button that he is currently to modify the second paragraph to show the text content ! In this example "P2" :

<div contenteditable="true"><p>P1</p><p>P2</p><p>P3</p></div>

在此先感谢您的帮助。

Nicolas

推荐答案

您可以在 mousedown 事件中检查选择按钮。以下内容将在所有主流浏览器中运行:

You could examine the selection in the mousedown event of the button. The following will work in all major browsers:

function getSelectionBoundaryContainerElement(start) {
    var container = null;
    if (typeof window.getSelection != "undefined") {
        var sel = window.getSelection();
        if (sel.rangeCount) {
            var range = sel.getRangeAt(0);
            range.collapse(start);
            container = range.startContainer;
            if (container.nodeType != 1) {
                container = container.parentNode;
            }
        }
    } else if (typeof document.selection != "undefined" && document.selection.type != "Control") {
        var textRange = document.selection.createRange();
        textRange.collapse(start);
        container = textRange.parentElement();
    }
    return container;
}

document.getElementById("yourButtonId").onmousedown = function() {
    alert(getSelectionBoundaryContainerElement().innerHTML);
}

这篇关于我如何知道在contentEditable情况下哪个元素正在修改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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