“This is the 15th day of my participation in the August Gwen Challenge.

Rich text knowledge recording

The rich text

  1. contenteditable=”true”

  2. document.execCommand

Since we can edit the div at will, how can we edit it? Currently, it seems that we can only enter text, how can we do other operations (such as bold, tilt, insert images, etc.) 🤔? The browser provides us with a method called Document. execCommand that allows us to manipulate the editable area above

ExecCommand execCommand execCommand execCommand execCommand execCommand execCommand execCommand execCommand
document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

/ / bold
document.execCommand('bold'.false.null);
// Add images
document.execCommand('insertImage'.false, url || base64);
// Wrap a paragraph of text around the P tag
document.execCommand('formatblock'.false.'<p>');
Copy the code
  1. Selection and Range objects

So normally we can use letrange=window.getSelection().getrangeat (0) to get the selected content. (getRangeAt accepts an index value, because there will be multiple ranges, and now there is only one, so write 0.)

In addition, several common methods for selecting objects are addRange, removeAllRanges, collapse, collapse to end, and more

  1. notice
  • Some students may not use the button tag, and then execute the command will be invalid, because clicking other tags will cause the first lose focus (or unknowingly suddenly lose focus), then execute the click event, there is no selection or cursor, so there will be no effect, this point should be noted.
  • We implemented the native document.execCommand method, and the browser itself maintains an undo stack and a redo stack for the editable area of Contenteditable so that we can perform forward and backward operations. If we adapted the native method, Will destroy the original stack structure, then need to maintain their own, that is troublesome
  • If you add scope in style, the style will not apply to the contents of the edit area, because the contents of the edit area will be created later, so either delete scope or use /deep/ (Vue is like this).

Paste without style

editor.addEventListener("paste".function(e) {
    e.preventDefault();
    var text = (e.originalEvent || e).clipboardData.getData('text/plain');
    document.execCommand("insertHTML".false, text);
});
Copy the code

The form uploads an image

<form target="iframe"></form>
iframe.addEventListener('load'.function(){});Copy the code