JavaScript execCommand("HiliteColor") 取消高亮

JavaScript execCommand("HiliteColor") unhighlight

JavaScript execCommand("HiliteColor") 通过添加跨度非常好地添加高亮显示,但我希望能够通过检查所选文本是否在高亮显示的跨度中来动态取消突出显示文本。然后是跨度中只有一半选定文本的磨损问题。我尝试自己添加跨度并尝试通过以下方式取消突出显示:

document.getElementsByClassName('highlight').remove();

alert(window.getComputedStyle(document.getElementById("pages"), null).getPropertyValue('background-color'));

alert(document.getElementById("pages").style.backgroundColor);

只是想看看我是否可以检查背景然后突出显示,或者我是否可以删除 class 突出显示。

我的项目在 codepen 上:https://codepen.io/pokepimp007/pen/wxGKEQ

回答

我创建了一个函数,它在单击按钮时采用颜色参数。单击删除突出显示按钮时,它会发送参数颜色 "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";
}

我看到你使用 jQuery,所以将 jQuery 标签添加到你的 post。

这样就可以了。

$('#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>