javascript - Detect if cursor is within li on content editable - Stack Overflow

I have working code that inserts <br> when you hit enter in a content editable div. (Browsers hav

I have working code that inserts <br> when you hit enter in a content editable div. (Browsers have various defaults of inserting <div> or <p> instead)

The problem is that it kills the default behavior of hitting enter to add another list item when building ordered or unordered lists. So my question is, can you detect if the text insertion point is within a list item, and if so, disable the javascript that deals with the enter key?

Working code: /

I have working code that inserts <br> when you hit enter in a content editable div. (Browsers have various defaults of inserting <div> or <p> instead)

The problem is that it kills the default behavior of hitting enter to add another list item when building ordered or unordered lists. So my question is, can you detect if the text insertion point is within a list item, and if so, disable the javascript that deals with the enter key?

Working code: http://jsfiddle/kthornbloom/RCdhS/

Share Improve this question edited Feb 4, 2013 at 19:10 kthornbloom asked Jan 30, 2013 at 16:56 kthornbloomkthornbloom 3,7403 gold badges32 silver badges47 bronze badges 2
  • 2 Question: Is jQuery available to you? Unsolicited pedantry: You probably either meant "caret" or, more likely, "cursor". EDIT: Never mind. I see that your demo uses jQuery. – isherwood Commented Jan 30, 2013 at 17:09
  • Good call, I updated it to say text insertion point since most people probably think of the "cursor" as the arrow you move with your mouse. – kthornbloom Commented Feb 4, 2013 at 19:11
Add a ment  | 

2 Answers 2

Reset to default 8

You need to do some DOM tree checking on the node containing the selection. Here's a demo that will work in all major browsers:

http://jsfiddle/CeMxs/2/

Code:

function isSelectionInsideElement(tagName) {
    var sel, containerNode;
    tagName = tagName.toUpperCase();
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount > 0) {
            containerNode = sel.getRangeAt(0).monAncestorContainer;
        }
    } 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/RCdhS/2/

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745612692a4636043.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信