javascript - 当插入符号在元素中时,是否有 CSS 选择器?

标签 javascript css caret

我有一个 contenteditable 元素,我希望其中的元素在插入符号位于其中时应用样式。

在此示例中,:hover 上的样式更改:

div{
caret-color: red;
}

span:hover {
  font-weight:bold;
}
<div contenteditable="true">
  <span>Sub element one</span> 
  text node
  <span>sub element two</span>
</div>

在这里您可以看到插入符,因为我将其设置为红色,但我将鼠标悬停在另一个 span 上:

example of the problem

有什么方法可以应用这样的样式,但当插入符位于元素内部时?以便红线周围的 span 中的文本为粗体?

解决方案如下所示:

style following caret

CSS 解决方案是理想的,但如果不可能,我会考虑 JS 解决方案。

最佳答案

使用 CSS?

不,没有 css 选择器。

使用 JavaScript?

是的,您可以使用 JavaScript 使用 .getSelection() 来做到这一点功能。

随着.getSelection()您可以获得 caret 的当前位置以及caret 所在的元素

window.getSelection().focusNode.parentElement // Returns DOM node

window.getSelection()

Returns a Selection object representing the range of text selected by the user or the current position of the caret.

https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

因此,使用此信息,您可以创建一个函数来设置插入符号所在元素的样式

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);
<div contenteditable id="contenteditable">
  <span>This is</span> some editable <span>content</span>
</div>

关于javascript - 当插入符号在元素中时,是否有 CSS 选择器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49923195/

相关文章:

javascript - 如何在机器人回复建议操作时隐藏/显示发送箱

css - 内容大小调整是否有指导方针?

css - express css 仅显示在索引页面上

html - 更改引导插入符的颜色(悬停在第一个 "li"元素上)

Java - JFormattedTextField 不允许首次尝试输入

javascript - 进出跨度时 tinyMCE 插入符号定位

javascript - 无法.replace样式属性吗?适用于 src、高度等

javascript - 对底层 npm 包进行更改

javascript - 我的简单 jquery 验证不起作用

html - 在所有浏览器中使用 column-count 时避免 paragraf 被破坏