检测光标是否在可编辑内容的 li 范围内

Detect if cursor is within li on content editable

本文关键字:li 范围内 编辑 光标 是否 检测      更新时间:2023-09-26

我有工作代码,当您在内容可编辑的div中按回车键时插入<br>(浏览器有插入<div><p>的各种默认值)

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

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

您需要在包含选择的节点上进行一些 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;
}

http://jsfiddle.net/RCdhS/2/

.on('keypress', 'document', function (e) {
    if (!$('li').focus();) {
    ...
    }
  }
});