检测光标是否在内容可编辑的内部

kth*_*oom 1 javascript css jquery contenteditable

我有一个工作代码,<br>当你在内容可编辑div中输入时插入.(浏览器有各种默认插入<div><p>替代)

问题是它在构建有序或无序列表时杀死了按Enter键以添加另一个列表项的默认行为.所以我的问题是,你能检测出文本插入点是否在列表项中,如果是,请禁用处理回车键的javascript?

工作代码:http://jsfiddle.net/kthornbloom/RCdhS/

Tim*_*own 6

您需要在包含选择的节点上执行一些DOM树检查.这是一个适用于所有主流浏览器的演示:

http://jsfiddle.net/CeMxs/2/

码:

function isSelectionInsideElement(tagName) {
    var sel, containerNode;
    tagName = tagName.toUpperCase();
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            containerNode = sel.getRangeAt(0).commonAncestorContainer;
        }
    } else if ( (sel = document.selection) && sel.type != "Control" ) {
        containerNode = sel.createRange().parentElement();
    }
    while (containerNode) {
        if (containerNode.nodeType == 1 && containerNode.tagName == tagName) {
            return true;
        }
        containerNode = containerNode.parentNode;
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)