Kei*_*ith 8 javascript css caret
我有一个contenteditable
元素,我希望其中的元素在插入符号位于其中时应用样式。
在此示例中,样式更改为:hover
:
div{
caret-color: red;
}
span:hover {
font-weight:bold;
}
Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true">
<span>Sub element one</span>
text node
<span>sub element two</span>
</div>
Run Code Online (Sandbox Code Playgroud)
在这里您可以看到插入符号,因为我将其设置为红色,但我将鼠标悬停在另一个上span
:
有什么方法可以应用这样的样式,但是当插入符号位于元素内部时?span
那么红线周围的文字是粗体吗?
解决方案如下所示:
CSS 解决方案是理想的,但如果不可能的话我会考虑 JS 解决方案。
用CSS?
不,没有css
选择器。
使用 JavaScript?
是的,您可以JavaScript
使用该.getSelection()
功能来做到这一点。
使用可以获取插入符.getSelection()
的当前位置并且插入符处于打开状态。element
window.getSelection().focusNode.parentElement // Returns DOM node
Run Code Online (Sandbox Code Playgroud)
window.getSelection()
返回一个 Selection 对象,表示用户选择的文本范围或插入符号的当前位置。
https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
因此,使用此信息,您可以创建一个函数来设置插入符所在元素的样式
window.getSelection().focusNode.parentElement // Returns DOM node
Run Code Online (Sandbox Code Playgroud)
var ctl = document.getElementById('contenteditable');
var selection;
function styleNode() {
// Get selection / caret position
selection = window.getSelection();
// Check if type is Caret and not Range (selection)
if(selection.type === 'Caret') {
// Remove styles
[...selection.focusNode.parentElement.parentElement.getElementsByTagName( "span" )].forEach( child => child.style.fontWeight = "normal" );
// Only style <span> elements
if(selection.focusNode.parentElement.tagName === 'SPAN') {
// Set style on element where caret is
selection.focusNode.parentElement.style.fontWeight = "bold";
}
}
}
// Removes styles on focusout
const reset = () => [...ctl.getElementsByTagName( "span" )].forEach( child => child.style.fontWeight = "normal" );
ctl.addEventListener("keyup", styleNode);
ctl.addEventListener("click", styleNode);
ctl.addEventListener("focusout", reset);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1246 次 |
最近记录: |