点击即可删除突出显示的文字

时间:2018-04-09 19:21:30

标签: javascript jquery

以下代码可让我突出显示文字。是否有任何方法可以通过

删除突出显示的文本(即文本不再突出显示)
  1. 点击突出显示的文字,然后按"删除"按钮或
  2. 双击它?
  3. 我也希望这个突出显示的文本也可以从元素highlights中删除。

    
    
    var lastSelection;
    document.addEventListener("selectionchange", function() {
      lastSelection = window.getSelection();
    });
    var highlights = document.createElement("div");
    
    function getRightClick(e) {
      var rightclick;
      if (!e) var e = window.event;
      if (e.which) rightclick = (e.which == 3);
      else if (e.button) rightclick = (e.button == 2);
      return rightclick; // true or false
    }
    
    function getSelectionCharacterOffsetsWithin(btnColor) {
      var selectedText = "null";
      if (typeof window.getSelection != "undefined") {
        var selection = window.getSelection();
        selectedText = selection.toString();
        var range = selection.getRangeAt(0);
        //Strip trailing punctation
        selectedText = selectedText.replace(/[\s.,!?:;'"-]+$/, "");
        //Leading space / quotes
        var offset = 0;
        var match = selectedText.match(/^[\s"']+/);
        if (match)
          offset = match[0].length;
        selectedText = selectedText.replace(/^[\s"']+/, "");
        if (selectedText === "") {
          alert("Error: you must select at least one character");
          tartOffset = 0, endOffset = 0, selectedText = "null";
        } else {
          var newInputid = parseInt(Math.random() * 10000);
          //This is code to keep word highlighted after selecting
          var newNode = document.createElement("span");
          newNode.classList.add('chosen');
          var previd = ("i" + newInputid);
          newNode.classList.add(previd);
          newNode.appendChild(range.extractContents());
          range.insertNode(newNode);
          var textSegment = $("." + previd);
          textSegment[0].style.backgroundColor = btnColor;
        }
      }
      return {
        text: selectedText,
        cid: previd
      };
    }
    
    $('.article').mousedown(function(event) {
      $('body').attr('mouse-top', event.clientY + window.pageYOffset);
      $('body').attr('mouse-left', event.clientX);
    
      if (!getRightClick(event)) {
        $('.entity_types').hide();
        document.getSelection().removeAllRanges();
      }
    });
    
    $('.article').mouseup(function(event) {
      if (lastSelection.toString().length > 1 && !getRightClick(event)) {
        $('.entity_types').css({
          display: 'block',
          position: 'absolute',
          top: event.clientY + 15,
          left: event.clientX + 10
        });
    
        $('.entity_types button').on('click', function(e) {
          e.preventDefault();
          var btnColor = $(this)[0].style.color;
          var selOffsets = getSelectionCharacterOffsetsWithin(btnColor);
          var selectedText = selOffsets.text;
          var selectedID = selOffsets.cid
          var txt = document.createTextNode(selectedText);
          highlights.appendChild(txt);
        });
      }
    });
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id='entity_class' class="entity_types">
      <button class="btn" style="color:green">Class 1</button>
      <button class="btn" style="color:red">Class 2</button>
      <button class="btn" style="color:purple">Class 3</button>
    </div>
    
    <div class="article" style="overflow-x:auto;">
      What is missing from this statement, and likely to be asked by lawmakers, is why it took a newspaper to discover this breach of Facebook's systems. And, once Facebook knew, why it didn't notify the public and regulators immediately - instead of doing
      everything it could to block the story.
    </div>
    &#13;
    &#13;
    &#13;

1 个答案:

答案 0 :(得分:1)

使用事件委派,双击span所有.chosen类将清除:

$('.article').on('dblclick', '.chosen', function() {
  (this).replaceWith(this.innerText);
});

示例:

var lastSelection;
document.addEventListener("selectionchange", function() {
  lastSelection = window.getSelection();
});
var highlights = document.getElementById("highlights");

function getRightClick(e) {
  var rightclick;
  if (!e) var e = window.event;
  if (e.which) rightclick = (e.which == 3);
  else if (e.button) rightclick = (e.button == 2);
  return rightclick; // true or false
}

function getSelectionCharacterOffsetsWithin(btnColor) {
  var selectedText = "null";
  if (typeof window.getSelection != "undefined") {
    var selection = window.getSelection();
    selectedText = selection.toString();
    var range = selection.getRangeAt(0);
    //Strip trailing punctation
    selectedText = selectedText.replace(/[\s.,!?:;'"-]+$/, "");
    //Leading space / quotes
    var offset = 0;
    var match = selectedText.match(/^[\s"']+/);
    if (match)
      offset = match[0].length;
    selectedText = selectedText.replace(/^[\s"']+/, "");
    if (selectedText === "") {
      alert("Error: you must select at least one character");
      tartOffset = 0, endOffset = 0, selectedText = "null";
    } else {
      var newInputid = parseInt(Math.random() * 10000);
      //This is code to keep word highlighted after selecting
      var newNode = document.createElement("span");
      newNode.classList.add('chosen');
      var previd = ("i" + newInputid);
      newNode.setAttribute('data-cid', previd);
      newNode.appendChild(range.extractContents());
      newNode.style.backgroundColor = btnColor;
      range.insertNode(newNode);
    }
  }
  return {
    text: selectedText,
    cid: previd
  };
}

$('.article').mousedown(function(event) {
  $('body').attr('mouse-top', event.clientY + window.pageYOffset);
  $('body').attr('mouse-left', event.clientX);

  if (!getRightClick(event)) {
    $('.entity_types').hide();
    document.getSelection().removeAllRanges();
  }
});

$('.article').mouseup(function(event) {
  if (lastSelection.toString().length > 1 && !getRightClick(event)) {
    $('.entity_types').css({
      display: 'block',
      position: 'absolute',
      top: event.clientY + 15,
      left: event.clientX + 10
    });
  }
});

$('.entity_types button').on('click', function(e) {
  e.preventDefault();
  var btnColor = $(this)[0].style.color;
  var selOffsets = getSelectionCharacterOffsetsWithin(btnColor);
  var selectedText = selOffsets.text;
  var selectedID = selOffsets.cid
  var txt = document.createTextNode(selectedText);
  var span = document.createElement('span');
  span.appendChild(txt);
  span.setAttribute('data-cid', selectedID);
  span.classList.add('highlighted');
  highlights.appendChild(span);
});

$('.article').on('dblclick', '.chosen', function() {
  var cid = this.getAttribute('data-cid');
  highlights.querySelector('[data-cid=' + cid + ']').remove();
  (this).replaceWith(this.innerText);
});
.highlighted:not(:last-child) {
  margin-right: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='entity_class' class="entity_types">
  <button class="btn" style="color:green">Class 1</button>
  <button class="btn" style="color:red">Class 2</button>
  <button class="btn" style="color:purple">Class 3</button>
</div>

<div class="article" style="overflow-x:auto;">
  What is missing from this statement, and likely to be asked by lawmakers, is why it took a newspaper to discover this breach of Facebook's systems. And, once Facebook knew, why it didn't notify the public and regulators immediately - instead of doing
  everything it could to block the story.
</div>

<br>

<div id="highlights"></div>