学无先后,达者为师

网站首页 前端文档 正文

JS选中文本高亮

作者:ZionHH 更新时间: 2022-05-12 前端文档

实现选中文本高亮,主要用到的两个API:

  1. Window.getSelection
    用于获取选中文本
  2. document.execCommand
    用于将选中文本高亮

在这里插入图片描述
完整代码如下

DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>demotitle>
  head>
  <body>
    <div onmouseup="highlight('yellow')">
      Window.getSelection 返回一个 Selection 对象,表示用户选择的文本范围或光标的当前位置。
      如果想要将 selection 转换为字符串,可通过连接一个空字符串("")或使用 String.toString() 方法。
      你还可以使用 Document.getSelection(),两个方法等价。
    div>

    <script>
      function highlight(color) {
        let range = null
        const sel = window.getSelection() // 选中文本

        console.log(sel.toString())
        if (sel.rangeCount && sel.getRangeAt) {
          range = sel.getRangeAt(0)
        }
        // 开启文档编辑
        document.designMode = 'on'
        if (range) {
          sel.removeAllRanges()
          sel.addRange(range)
        }
        document.execCommand('BackColor', false, color)

        document.designMode = 'off'
        // 去掉默认选中的蓝色
        window.getSelection().empty()
      }
    script>
  body>
html>

原文链接:https://blog.csdn.net/z291493823/article/details/122646795

栏目分类
最近更新