CSS ::元素的焦点在于满足

pvo*_*orb 12 javascript html5 focus contenteditable css3

如果您有以下HTML:

<div contenteditable="true">
  <p>The first paragraph</p>
  <p>The second paragraph</p>
</div>
Run Code Online (Sandbox Code Playgroud)

有没有一种办法风格,是被从所有其他段落编辑不同的段落divcontenteditable

div > p:focus { border: 1px solid red }
Run Code Online (Sandbox Code Playgroud)

不会应用于正在编辑的段落.

这是一个你可以玩的JSFiddle.

如何设置正在编辑段落(<p>-tag)的样式?

我更喜欢仅使用CSS的解决方案,但也许我必须使用JavaScript.

编辑:

由于我们找不到纯CSS解决方案(并且使用:hover对我来说不是真正的解决方案),我现在正在寻找一些JavaScript,class="focus"它们在正在编辑的节点上设置属性.

pvo*_*orb 9

我想我找到了解决方案.

使用以下代码片段,您可以在选择更改时获取当前插入符号位置的父元素.

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;
Run Code Online (Sandbox Code Playgroud)

这里我outline手动更改属性,但您当然可以添加类属性并通过CSS设置样式.

您仍然需要手动检查我是否selectedElement<div>具有该contenteditable属性的子项.但我认为你可以得到基本的想法.

这是更新的JSFiddle.

编辑:我更新了代码以及JSFiddle,使其可以在Firefox和Internet Explorer 9+中使用.不幸的是,这些浏览器没有onselectionchange事件处理程序,所以我不得不使用onkeyuponmouseup.