CSS on:专注于contenteditable的子对象

Ric*_*ick 5 css contenteditable

我试图检测focus元素的子元素,以contenteditable实现纯CSS样式。(我知道我可以使用JS来检测到这一点,添加一个额外的类并以这种方式进行操作,但这太漫长了。)

基本上,我有一些类似的东西:

<div contenteditable="true">
  Some text <span class="edit">that</span> goes here.
</div>
Run Code Online (Sandbox Code Playgroud)

我按照以下方式尝试了CSS:

.edit:focus {
  color: #FF0000;
}
Run Code Online (Sandbox Code Playgroud)

我希望span当插入符插入时改变颜色,但显然焦点仅应用于的div设置contenteditable,而不应用于其任何子级。我曾尝试对施加一秒钟contenteditable的时间span,但除了采取一种非常草率的方法外,它还是无法正常工作。

这个问题有方法解决吗?

Tim*_*own 2

由于contenteditable元素中的元素通常无法接收焦点的限制,我建议<span>当选择包含在元素中时,通过向元素添加一个类来伪造它,您可以通过监视选择的更改来实现这一点(您将拥有在 Firefox 中使用鼠标和键盘事件并轮询彻底性,直到selectionchange在该浏览器中实现该事件)。

var selectionContainer = null;

function updateSelectionContainer() {
  var newSelectionContainer = null;
  var sel;
  if (window.getSelection && (sel = window.getSelection()).rangeCount) {
    newSelectionContainer = sel.getRangeAt(0).commonAncestorContainer;

    // Ensure we have an element rather than a text node
    if (newSelectionContainer.nodeType != 1) {
      newSelectionContainer = newSelectionContainer.parentNode;
    }
  }
  if (newSelectionContainer != selectionContainer) {
    if (selectionContainer) {
      selectionContainer.className = selectionContainer.className.replace(/ ?containsSelection/, "");
    }
    if (newSelectionContainer) {
      newSelectionContainer.className +=
        (newSelectionContainer.className ? " containsSelection" : "containsSelection");
    }
    selectionContainer = newSelectionContainer;
  }
}

if ("onselectionchange" in document) {
  document.onselectionchange = updateSelectionContainer;
} else {
  var el = document.getElementById("editor");
  el.onmousedown = el.onmouseup = el.onkeydown = el.onkeyup = el.oninput = updateSelectionContainer;
  window.setInterval(updateSelectionContainer, 100);
}
Run Code Online (Sandbox Code Playgroud)
div {
  font-size: 200%;
}

.edit.containsSelection {
  color: red;
  font-weight: bold;
}
Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true" id="editor">
  Some text <span class="edit">that</span> goes here.
</div>
Run Code Online (Sandbox Code Playgroud)