CSS on:专注于满足于孩子的孩子

时间:2015-04-30 09:08:18

标签: css contenteditable

我试图在focus元素的子元素上检测contenteditable,以用于纯CSS样式。 (我知道我可以通过JS检测到这一点,添加一个额外的类并以这种方式执行,但这是如此冗长。)

基本上,我有以下几点:

<div contenteditable="true">
  Some text <span class="edit">that</span> goes here.
</div>

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

.edit:focus {
  color: #FF0000;
}

我希望span在插入符号时更改颜色,但显然焦点仅适用于设置为div的{​​{1}},而不适用于其中的任何子项。我已经尝试将第二个contenteditable应用于contenteditable,但除了是一个非常草率的方法之外,它无论如何都不起作用。

有解决方法吗?

4 个答案:

答案 0 :(得分:2)

我的理解是可以获得焦点(自动)的元素类型是有限的。

请参阅SO Question

一种选择是将tabindex添加到范围。

&#13;
&#13;
body {
  font-size: 3rem;
}
div[contenteditable=true] .edit:focus {
  color: #FF0000;
}
&#13;
<div contenteditable="true">Some text <span class="edit" tabindex="0">that</span> goes here.</div>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

:focus > .edit { color: #cc0000; }

<div contenteditable="true">Some text <span class="edit">that</span> goes here.</div>
<div contenteditable="true">Some text that goes here.</div>

答案 2 :(得分:1)

由于contenteditable元素中的元素通常无法获得焦点的限制,我建议通过在其中包含选择的<span>元素中添加一个类来伪装它,可以通过监视更改选择(您必须使用鼠标和键盘事件以及在Firefox until the selectionchange event is implemented in that browser中轮询彻底性)。

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);
}
div {
  font-size: 200%;
}

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

答案 3 :(得分:0)

只需添加此项而不是:焦点。 Fiddle.

.edit {
  color: #f00;
}