如果您具有以下HTML:
<div contenteditable="true">
<p>The first paragraph</p>
<p>The second paragraph</p>
</div>
有没有一种方法可以设置正在编辑的段落的样式,使其不同于
div
的contenteditable
中的所有其他段落?div > p:focus { border: 1px solid red }
不会应用于正在编辑的段落。
这是您可以使用的 JSFiddle 。
如何为正在编辑的段落(
<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
属性,但是您当然可以添加class属性并通过CSS设置样式。您仍然需要使用
selectedElement
属性手动检查<div>
是否是我们contenteditable
的子级。但我认为您可以掌握基本思路。这是 updated JSFiddle 。
编辑:我更新了代码以及JSFiddle,使其也可以在Firefox和Internet Explorer 9+中使用。不幸的是,这些浏览器没有
onselectionchange
事件处理程序,因此我不得不使用onkeyup
和onmouseup
。关于javascript - CSS::contenteditable中元素的焦点,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16832749/