Insert character at specific point but preserving tags?

后端 未结 2 896
無奈伤痛
無奈伤痛 2021-01-18 02:22

Update #2

Okay, more testing ensues. It looks like the code works fine when I use a faux spacer, but the regex eventually fails. Specifically, the following scenari

2条回答
  •  长情又很酷
    2021-01-18 03:16

    Here is a solution that supports all the features from your requirements:

    HTML:

    First Line Second Line Third Line Forth Line

      CSS:

      .space {
          display: inline-block;
          width: 100%;
      }
      .highlighting {
          background-color: green;
      }
      

      JavaScript:

      var text,
          output,
          unwrapContents,
          mergeElements,
          clearSelection,
          clearHighlighting,
          mergeHighlighting,
          handleCopy;
      
      unwrapContents = function unwrapContents(element) {
          while(element.firstChild !== null) {
              element.parentNode.insertBefore(element.firstChild, element);
          }
          element.parentNode.removeChild(element);
      };
      
      mergeElements = function mergeElements(startElement, endElement) {
          var currentElement;
          endElement = endElement.nextSibling;
          while((currentElement = startElement.nextSibling) !== endElement) {
              startElement.appendChild(currentElement);
          }
      };
      
      clearSelection = function clearSelection() {
          if (document.selection) {
              document.selection.empty();
          } else if (window.getSelection) {
              window.getSelection().removeAllRanges();
          }
      };
      
      clearHighlighting = function clearHighlighting(target, exception) {
          $('.highlighting', target).each(function(index, highlighting) {
              if(highlighting !== exception) {
                  unwrapContents(highlighting);
              }
          });
          target.normalize();
      };
      
      mergeHighlighting = function mergeHighlighting() {
          var i, j;
          // Remove internal highlights
          $('.highlighting', text).filter(function() {
              return this.parentNode.className === 'highlighting';
          }).each(function(index, highlighting) {
              unwrapContents(highlighting);
          });
          text.normalize();
          // Merge adjacent highlights
          first:
          for(i=0; i

      Here is a working example http://jsbin.com/efohit/3/edit

    提交回复
    热议问题