实现文本选中变色

单个文本变色

    <div id="myText">vfadsfgase</div>
const myText = document.getElementById('myText');
myText.addEventListener('mouseup', () => {
  const selection = window.getSelection();
  if (selection.toString() !== '') {
    const range = selection.getRangeAt(0);
    const highlight = document.createElement('span');
    highlight.style.backgroundColor = 'yellow'; // 设置背景色
    highlight.appendChild(range.extractContents());
    range.insertNode(highlight);
  }
});

多个文本变色

    highlightSelection() {
      const selection = window.getSelection()
      if (selection.toString() !== '') {
        const range = selection.getRangeAt(0)
        const cloneRange = range.cloneRange() // 创建副本
        const textNodes = this.getTextNodes(cloneRange) // 获取所有文本节点
        const selectedText = selection.toString()
        textNodes.forEach((node) => {
          const nodeText = node.nodeValue
          const index = nodeText.indexOf(selectedText)
          console.log("index",index);
          if (index !== -1) {
            const highlight = document.createElement('span')
            highlight.style.backgroundColor = 'yellow' // 设置背景色
            highlight.appendChild(document.createTextNode(selectedText))
            const startOffset = index
            const endOffset = index + selectedText.length
            const nodeRange = document.createRange()
            nodeRange.setStart(node, startOffset)
            nodeRange.setEnd(node, endOffset)
            nodeRange.deleteContents()
            nodeRange.insertNode(highlight)
          }
        })
      }
    },
    getTextNodes(range) {
      const nodes = []
      const walker = document.createTreeWalker(range.commonAncestorContainer, NodeFilter.SHOW_TEXT, null, false)
      let node
      while ((node = walker.nextNode())) {
        nodes.push(node)
      }
      return nodes
    },

你可能感兴趣的:(chrome,前端)