CSS::contenteditable中元素的焦点

如果您具有以下HTML:

<div contenteditable="true">

<p>The first paragraph</p>

<p>The second paragraph</p>

</div>

有没有一种办法风格,正在编辑不同于所有其他段落的段落divcontenteditable

div > p:focus { border: 1px solid red }

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

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

我希望使用仅CSS的解决方案,但也许我必须使用JavaScript。

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

回答:

我想我找到了解决方案。

通过以下代码片段,您可以在选择更改时将父元素置于当前插入符号位置。

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;

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

您仍然必须手动检查该属性是否selectedElement是我们的子级。但我认为您可以掌握基本思路。<div>``contenteditable

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

以上是 CSS::contenteditable中元素的焦点 的全部内容, 来源链接: utcz.com/qa/433876.html

回到顶部