[英]Permanently change color of selected text and revert in HTML with JavaScript
我希望能够 select 文本单击按钮并更改文本颜色 e。 不再选择文本后,文本颜色更改应保持不变。
我知道已经有很多解决方案可以使用CSS做到这一点。 然而; 我希望能够访问节点,以便在单击另一个按钮时,我可以恢复颜色更改。 我尝试查看window.getSelection()
和Ranges
和DocumentFragment
,但我无法理解如何 select DocumentFragment 中的节点,修改每个节点,将其插入正确的参考 Z4757FE076FD492A8BEEZA6 中的文档我可以在稍后的单击中再次将颜色更改回黑色。
我还发现这个线程基本上做了我想做的事情,但它使用了已过时的 execCommand。
我不想要 CSS 解决方案,也不想要使用 jQuery 的解决方案。
下面是我正在使用的具有类似 html 结构的 js 代码和 codepen。
我有 2 个按钮,一个用于更改选择的颜色,一个用于在不再选择文本后恢复选择的颜色。
我正在使用window.getSelection()
来获取所选文本的Selection
。 我检查Selection
是否有效,然后使用getRangeAt(0)
获取范围,然后调用extractContents()
。
这是困难的部分,因为:
DocumentFragment
,那么如何将DocumentFragment
重新插入到从中提取的 position 中?DocumentFragment
styles 中的节点var changeColorButton = document.getElementById('xyz');
var revertColor = document.getElementById('zyx');
const changeSelectionColor = () => {
let selection = window.getSelection()
if (selection) {
let range = selection.getRangeAt(0)
if (range) {
let frag = range.extractContents();
}
/*
2 problems:
1. accessing each node in the DocumentFragment and modifying the style then re-inserting into the correct spot
2. Creating a reference to this fragment for revertColorChange() to use to change the color back to black
*/
}
}
const revertColorChange = () => {
// revert color
}
changeColorButton.addEventListener('click', changeSelectionColor);
<!DOCTYPE html>
<html>
<body>
<button onClick="changeColor()">Change color</button><br/>
<button onClick="changeColorBack()">Change to previous color</button>
<p id="demo">Javascript</p>
<script>
changeColor=()=>{
document.getElementById("demo").style.color ="red"
}
changeColorBack=()=>{
document.getElementById("demo").style.color ="black"
}
</script>
</body>
</html>
这是你想要的?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.