JavaScript execCommand("HiliteColor")通过添加跨度来很好地添加高亮显示,但我希望能够通过检查所选文本是否在高亮显示的跨度中来动态取消高亮显示文本。那么就有一个问题,就是在一个跨度中只有一半的选定文本。我尝试自己添加跨度,并尝试通过以下方式取消高亮显示它们:
document.getElementsByClassName('highlight').remove();
alert(window.getComputedStyle(document.getElementById("pages"), null).getPropertyValue('background-color'));
alert(document.getElementById("pages").style.backgroundColor);看看我是否可以检查背景然后高亮显示,或者是否可以删除类高亮显示。
我的项目在codepen上:https://codepen.io/pokepimp007/pen/wxGKEQ
应答
我创建了一个函数,它在单击按钮时接受一个颜色参数。单击删除高亮显示按钮时,将发送参数color "transparent":
function Highlight(color) {
document.designMode = "on";
var sel = window.getSelection();
sel.removeAllRanges();
var range = document.createRange();
range.setStart(editor.startContainer, editor.startOffset);
range.setEnd(editor.endContainer, editor.endOffset);
sel.addRange(range);
if (!sel.isCollapsed) {
if (!document.execCommand("HiliteColor", false, color)) {
document.execCommand("BackColor", false, color);
}
}
sel.removeAllRanges();
document.designMode = "off";
}https://stackoverflow.com/questions/51558725
复制相似问题