CSS: :focus of elements within contenteditable

后端 未结 3 1634
南旧
南旧 2020-12-03 03:49

If you have the following HTML:

The first paragraph

The second paragraph

3条回答
  •  -上瘾入骨i
    2020-12-03 04:04

    I think I found a solution.

    With the following code snippet you can get the parent element at the current caret position when the selection changes.

    var selectedElement = null;
    function setFocus(e) {
      if (selectedElement)
        selectedElement.style.outline = 'none';
    
      selectedElement = window.getSelection().focusNode.parentNode;
      // walk up the DOM tree until the parent node is contentEditable
      while (selectedElement.parentNode.contentEditable != 'true') {
        selectedElement = selectedElement.parentNode;
      }
      selectedElement.style.outline = '1px solid #f00';
    };
    document.onkeyup = setFocus;
    document.onmouseup = setFocus;
    

    Here I change the outline property manually but you could of course add a class attribute and set the style via CSS.

    You still have to manually check if selectedElement is a child of our

    with the contenteditable attribute. But I think you can get the basic idea.

    Here's the updated JSFiddle.

    EDIT: I updated the code as well as the JSFiddle to make it work in Firefox and Internet Explorer 9+, too. Unfortunately these Browsers do not have a onselectionchange event handler, so I had to use onkeyup and onmouseup.

提交回复
热议问题