在iframe设计模式下获取插入符号的父元素 [英] Get parent element of caret in iframe design mode

查看:157
本文介绍了在iframe设计模式下获取插入符号的父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

这是一个执行此操作的功能,改编自对类似问题的回答

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;
}

使用示例:

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

这篇关于在iframe设计模式下获取插入符号的父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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