我正在努力创建一个功能丰富的文本编辑器,它可以模拟您在 MS word 和 google docs 等全尺寸文字处理器中找到的一些功能。我正在尝试将样式(粗体、斜体、突出显示等)应用于用户选择的文本。
我已经将完成这项工作的以下代码放在一起,但前提是突出显示的文本不跨越 html 元素。
const hightlightBtn = document.querySelector('.btn');
hightlightBtnS.addEventListener('click', () => {
const selected = window.getSelection().getRangeAt(0);
console.log(selected);
highlightElement(selected);
});
function highlightElement(range){
const newNode = document.createElement('div');
newNode.setAttribute(
'style',
'background-color: yellow; display: inline;'
)
range.surroundContents(newNode);
};
如果我尝试突出显示来自两个段落的文本(并包含在单独的标签中),则会出现错误:Uncaught DOMException: Failed to execute 'surroundContents' on 'Range': The Range has partially selected a non-Text node.
这似乎是surroundContents() 方法的问题。
在此方法的 MDN 引用资料中,我发现以下内容:
An exception will be thrown, however, if the Range splits a non-Text node with only one of its boundary points. That is, unlike the alternative above, if there are partially selected nodes, they will not be cloned and instead the operation will fail.
有什么办法可以在仍然使用环绕内容的同时解决这个问题?或者任何人都可以帮我找出另一种将样式应用于用户选择的文本的方法吗?
最佳答案
为什么不简单地使用 CSS?
p::selection, p ::selection {
background-color: green;
color: #fff;
}
<p>Mark some text <i>here</i> in this paragraph.</p>
伪选择器
::selection
具有非常广泛的浏览器支持,甚至可以追溯到 IE 9:关于javascript - 有没有办法使用 javascript 将样式应用于突出显示的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63539926/