【问题标题】:Get parent element of caret in iframe design mode在 iframe 设计模式下获取插入符号的父元素
【发布时间】:2013-01-27 10:43:50
【问题描述】:

我想知道iframedesignMode = 'on' 中插入符号的父元素是什么。 原因是想知道当前用户是否正在输入p 标签。

【问题讨论】:

    标签: javascript html iframe rich-text-editor designmode


    【解决方案1】:

    这是一个执行此操作的函数,改编自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;
    }
    

    使用示例:

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

    【讨论】:

    • 我不明白isStart 是什么意思?
    • @Omid:该函数还处理获取包含选择边界的元素的一般情况。 isStart 指示是否使用选择开始或结束边界。在折叠选择的情况下(即只是一个插入符号),它们是相同的,因此 isStart 的值无关紧要。
    猜你喜欢
    • 1970-01-01
    • 2015-04-22
    • 2014-05-08
    • 1970-01-01
    • 2017-04-22
    • 1970-01-01
    • 2010-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多