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
答案
我创建了一个函数,该函数在单击按钮时带有一个颜色参数。单击删除突出显示按钮时,它将发送参数颜色“透明”:
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";
}
答案 0 :(得分:2)
我看到您使用jQuery,因此在您的帖子中添加了jQuery标签。
这可以解决问题。
$('#removeHighlight').on('click', function(){
$('.highlight').each(function(){
$(this).replaceWith($(this).text());
})
})
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a stupid bit of text with <span class="highlight">highlight_1</span> in it to display the power of jquery to do stuff like removing <span class="highlight">highlight_2</span> in a html document. Go on and press the button to see the <span class="highlight">highlight_3</span> magic.</p>
<button id="removeHighlight">Remove</button>
如果只想删除一个突出显示,请执行此操作。
$('#removeHighlight').on('click', function(){
$('.highlight').first().replaceWith($('.highlight').first().text());
})
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a stupid bit of text with <span class="highlight">highlight_1</span> in it to display the power of jquery to do stuff like removing <span class="highlight">highlight_2</span> in a html document. Go on and press the button to see the <span class="highlight">highlight_3</span> magic.</p>
<button id="removeHighlight">Remove 1</button>
或者如果您要在单击时将其删除
$('p').on('click', '.highlight', function(){
$(this).replaceWith($(this).text());
})
.highlight {
background: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a stupid bit of text with <span class="highlight">highlight_1</span> in it to display the power of jquery to do stuff like removing <span class="highlight">highlight_2</span> in a html document. Go on and press the button to see the <span class="highlight">highlight_3</span> magic.</p>