web dom api in Selection and Range

If you did wysiwyg this app, a very vexing question is how to ensure the implementation of bold, holding position where the previous mouse italic formatting and other operations. To properly solve this problem, it must Selection and Range of api clear out.

https://javascript.info/selection-range

Selection and Range

js possible to obtain information of the current selected area, or can choose to select some or all of the contents, clear the selected portion of the document, using a tag to heart wrapping operation. The cornerstone of all these operations is Selction and Range Both api.

Range

The basic concept is that selection area Range: it is a pair of boundary points, namely the range defined start and end.

Each end point is relative to the parent DOM Node offset information expressed. If the father node is an element element node, then the offset number is the number of child, child to text node, it is the position of the text. We have examples to illustrate, we have to select some of the content, for example:

First, we can create a range:

let range = new Range();

Then we can use  range.setStart (node, offset), range.setEnd (node, offset)  two api function to set the boundary range, for example, if we html code as follows:

<p id="p">Example: <i>italic</i> and <b>bold</b></p>

Dom tree corresponding follows:

Let's selection  Example: <i> italic </ i>  this part. It is actually in front of the two sons of the parent node p element (including text node)

Let's look at the actual code:

<p id="p">Example: <i>italic</i> and <b>bold</b></p>

<script>
  let range = new Range();

  range.setStart(p, 0);
  range.setEnd(p, 2);

  // toString of a range returns its content as text (without tags)
  alert(range); // Example: italic

  // apply this range for document selection (explained later)
   document.getSelection().removeAllRanges();
  document.getSelection().addRange(range);
</script>
  • range.setStart (p, 0) - is the first to set the selection range 0 child nodes of the parent element p (i.e. a Node text:   Example:  )
  • range.setEnd (p, 2) - specifies that the range will be extended to p parent element of the second child (that is, "and" this text node), but note here that does not include the amount that is actually the first to a child, and therefore is node i

Note that we do not actually need to use the same reference node node setStart and setEnd call, covering a range of possible extension to multiple nodes irrelevant. The only caveat is that end must be behind the start of

Select the text portion of nodes, but not all

Imagine the following scenario we do select operations:

This can be easily achieved using the code, we need to do is use the offset position relative to the text nodes of the set start and end just fine.

We need to create a range:

1. range of start is the first p element child of the father position 2, which is "ample:"

2.range the end b father is an element of position 3, which is "bol"

<p id="p">Example: <i>italic</i> and <b>bold</b></p>

<script>
  let range = new Range();

  range.setStart(p.firstChild, 2);
  range.setEnd(p.querySelector('b').firstChild, 3);

  alert(range); // ample: italic and bol

  // use this range for selection (explained later)
  document.getSelection().removeAllRanges();??
  window.getSelection().addRange(range);
</script>

In this case, range attribute values ​​as shown below:

  • startContainer, startOffset- respectively designated start point node, and the node with respect to the offset, this embodiment is the first text node child node of the node p, and the second position
  • endContainer, endOffset- specify offset end point node, and, in this case text node is the first child node of the node b, and position 3
  • collapsed - Boolean value, if the star and point to the same end point, then a point is true, also means that no content is selected in the range, in this case the value is false
  • commonAncestorContainer - the most recent common ancestor of all nodes in the node in this range, in this case, the node p

Range method methods

There are many useful target range method for operating a range:

Setting range of the start:

setEnd(node, offset) set end at: position offset in node
setEndBefore(node) set end at: right before node
setEndAfter(node) set end at: right after node

As previously demonstrated that, node can be a text or element node, for text node, offset mean ignoring a few characters, and if element node, refers to the number of child nodes ignored

Other methods:

  • selectNode(node) set range to select the whole node
  • selectNodeContents(node) set range to select the whole node contents
  • collapse(toStart) if toStart=true set end=start, otherwise set start=end, thus collapsing the range
  • cloneRange() creates a new range with the same start/end

A method for operating a content range:

  • deleteContents() – remove range content from the document
  • extractContents() – remove range content from the document and return as DocumentFragment
  • cloneContents() – clone range content and return as DocumentFragment
  • insertNode(node) – insert node into the document at the beginning of the range
  • surroundContents(node) – wrap node around range content. For this to work, the range must contain both opening and closing tags for all elements inside it: no partial ranges like <i>abc.

With these useful methods, we can basically do anything for the selected nodes, see below a parity complicated example:

Click buttons to run methods on the selection, "resetExample" to reset it.

<p id="p">Example: <i>italic</i> and <b>bold</b></p>

<p id="result"></p>
<script>
  let range = new Range();

  // Each demonstrated method is represented here:
  let methods = {
    deleteContents() {
      range.deleteContents()
    },
    extractContents() {
      let content = range.extractContents();
      result.innerHTML = "";
      result.append("extracted: ", content);
    },
    cloneContents() {
      let content = range.cloneContents();
      result.innerHTML = "";
      result.append("cloned: ", content);
    },
    insertNode() {
      let newNode = document.createElement('u');
      newNode.innerHTML = "NEW NODE";
      range.insertNode(newNode);
    },
    surroundContents() {
      let newNode = document.createElement('u');
      try {
        range.surroundContents(newNode);
      } catch(e) { alert(e) }
    },
    resetExample() {
      p.innerHTML = `Example: <i>italic</i> and <b>bold</b>`;
      result.innerHTML = "";

      range.setStart(p.firstChild, 2);
      range.setEnd(p.querySelector('b').firstChild, 3);

      window.getSelection().removeAllRanges();
      window.getSelection().addRange(range);
    }
  };

  for(let method in methods) {
    document.write(`<div><button onclick="methods.${method}()">${method}</button></div>`);
  }

  methods.resetExample();
</script>

In addition, there are some of the more range of api for rarely used, https: //developer.mozilla.org/en-US/docs/Web/API/Range

Selection

Range is used to manage a common object of selection ranges. We can create these objects range, then passed to the dom api

The document selection is characterized by a Selection object, which can be  window.getSelection () or document.getSelection ()  is obtained.

It may include a selection Ranges 0 or more, but in practical use, allowing only the selected plurality firefox Ranges, which needs to be achieved by ctrl + click, such as the following figure:

Attribute selection object

And similar range, but also a selection start, referred to as "anchor", and one end, referred to as "focus", the main attributes are as follows:

  • anchorNode – the node where the selection starts,
  • anchorOffset – the offset in anchorNode where the selection starts,
  • focusNode – the node where the selection ends,
  • focusOffset – the offset in focusNode where the selection ends,
  • isCollapsed – true if selection selects nothing (empty range), or doesn’t exist.
  • rangeCount – count of ranges in the selection, maximum 1 in all browsers except Firefox.

selection events

1. elem.onselectstart - When a selection began elem from this element, such as when the user presses the button while dragging the mouse when the event occurs. Note that, if the elem is prevent default, the event does not occur

2. document.onselectionchange, this event can only take place in the document, as long as the selection changes will trigger the event

See the following code

selection of commonly used methods:

  • getRangeAt(i) – get i-th range, starting from 0. In all browsers except firefox, only 0 is used.
  • addRange(range) – add range to selection. All browsers except Firefox ignore the call, if the selection already has an associated range.
  • removeRange(range) – remove range from the selection.
  • removeAllRanges() – remove all ranges.
  • empty() - alias to removeAllRanges

The following method of operation without the object range can be done directly underlying corresponding function:

  • collapse(node, offset) – replace selected range with a new one that starts and ends at the given node, at position offset.
  • setPosition(node, offset) - alias to  collapse.
  • collapseToStart() – collapse (replace with an empty range) to selection start,
  • collapseToEnd() – collapse to selection end,
  • extend(node, offset) – move focus of the selection to the given node, position offset,
  • setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset) – replace selection range with the given start anchorNode/anchorOffset and end focusNode/focusOffset. All content in-between them is selected.
  • selectAllChildren(node) – select all children of the node.
  • deleteFromDocument() – remove selected content from the document.
  • containsNode(node, allowPartialContainment = false) – checks whether the selection contains node (partically if the second argument is true)

Let us look at the following example code and its effects:

Selection in form controls

Form elements, such as input, textarea provides more api for selection operation and processing without the object selection or range. Because the input value is only text, rather than html, so there is no need to provide these objects selection and range, things will get easier.

  • input.selectionStart – position of selection start (writeable),
  • input.selectionEnd – position of selection start (writeable),
  • input.selectionDirection – selection direction, one of: “forward”, “backward” or “none” (if e.g. selected with a double mouse click)

input.onselect – triggers when something is selected.

 

Guess you like

Origin www.cnblogs.com/kidsitcn/p/11628822.html