gpt4 book ai didi

:focus within child of contenteditable 上的 CSS

转载 作者:技术小花猫 更新时间:2023-10-29 11:32:45 29 4
gpt4 key购买 nike

我正在尝试检测 focuscontenteditable 元素的子元素上,以实现纯 CSS 样式。 (我知道我可以用 JS 检测到这一点,添加一个额外的类并那样做,但那太啰嗦了。)

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

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

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

.edit:focus {
color: #FF0000;
}

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

有解决办法吗?

最佳答案

由于 contenteditable 中元素的限制元素通常无法获得焦点,我建议通过在 <span> 中添加一个类来伪装它element when the selection is contained within it, which you can do by monitoring the selection for changes (you'll have to use mouse and keyboard events and polling for thoroughness in 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>

关于:focus within child of contenteditable 上的 CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29963546/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com