Get parent element of caret in iframe design mode

≯℡__Kan透↙ 提交于 2019-12-25 02:27:07

问题


I want to know what is the parent element of caret in an iframe with designMode = 'on'. The reason is that want to know if currently user is typing in a p tag.


回答1:


Here's a function to do this, adapted from an answer to a similar question:

function getSelectionBoundaryElement(win, isStart) {
    var range, sel, container = null;
    var doc = win.document;

    if (doc.selection) {
        // IE branch
        range = doc.selection.createRange();
        range.collapse(isStart);
        return range.parentElement();
    } else if (win.getSelection) {
        // Other browsers
        sel = win.getSelection();

        if (sel.rangeCount > 0) {
            range = sel.getRangeAt(0);
            container = range[isStart ? "startContainer" : "endContainer"];

            // Check if the container is a text node and return its parent if so
            if (container.nodeType === 3) {
                container = container.parentNode;
            }
        }
    }
    return container;
}

Example use:

var iframe = document.getElementById("your_iframe_id");
var caretElement = getSelectionBoundaryElement(iframe.contentWindow, true);


来源:https://stackoverflow.com/questions/14546568/get-parent-element-of-caret-in-iframe-design-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!