选中内容自动弹出复制、翻译按钮,怎么实现的?js获取页面光标选中的内容

879 阅读2分钟

选中内容自动弹出复制、翻译按钮,怎么实现的?js获取页面光标选中的内容

一、需求场景描述:

选中页面一段内容后,自动弹出【翻译】、【拨号】、【复制】等场景,并不少见。那么这些需求在web前端是怎么实现的?

需求分解:

1.获取光变选中的内容

2.获取到内容后弹出对应的功能按钮

3.编写对应功能的逻辑,如【拨号】或【复制】等

通过需求分解,我们知道,获取选中内容以及选中后的时机是关键,后面就是各自的业务逻辑了。

表示获取页面上用户选取选中的内容,例如使用鼠标选中某一段内容,可以通过window.getSelection()获取选中的内容。在一些需要对选中内容即时【划线】、【翻译】或弹出【复制】等功能键的时候,可能非常有用。通常可以结合单击、双击、长按等事件,按需配套使用。

二、相关技术介绍:window.getSelection()

相关用法

// getSelection 的基本用法
const selection = window.getSelection() ;

// selection 是一个 Selection 对象。 如果想要将 selection 转换为字符串,
// 可通过连接一个空字符串("")或使用 String.toString() 方法。例如:

const selectionStr = window.getSelection().toString ;
console.log("选中的内容:" + selectionStr)

注意事项:

目前在Firefox, Edge (非 Chromium 版本) 及 Internet Explorer 中,getSelection() 对 及 元素不起作用。

各大浏览器兼容性:

image.png

三、获取光标选中内容demo完整代码

效果图如下:

image.png

demo实现思路

1.通过监听鼠标mouseup事件,触发window.getSelection()获取选中内容

2.通过界固定定位fixed和鼠标事件的坐标实现跟随鼠标展示功能按钮

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>js实现获取光变选中的内容</title>
  <style>
      #tem {
          display: none;
          position: fixed;
          top: 0;
          left: 0;
          background: #eeeeee;
          border-radius: 4px;
          padding: 5px 10px;
      }

      span {
          margin: 5px;
          padding: 2px 7px;
          display: inline-block;
          border: 1px solid #B4B2B2FF;
          border-radius: 4px;
          cursor: pointer;
      }

  </style>
</head>
<body>

<h1>这是一个电话:10086</h1>
<div id="tem">
  <span onclick="clickCopy()">复制</span> <br />
  <span onclick="clickTranslate()">翻译</span> <br />
  <span onclick="clickTel()">拨号</span>
</div>
<script>
  window.onload = function() {
    // 文档加载解析完成后,监听mouseup事件
    window.addEventListener("mouseup", function(e) {
      document.getElementById("tem").style.display = "none";
      getSelectionText(e);
    });
  };

  // 获取光变选中的内容
  function getSelectionText(e) {
    try {
      const selection = window.getSelection();
      let selectionText = selection.toString();
      if (!selectionText) return;
      showTemplate(e, selection);
    } catch (error) {
      alert("该浏览器不支持此操作");
      console.log(error);
    }
  }

  function showTemplate(e, selection) {
    const selectionText = selection.toString();
    // 展示按钮选型,并通过获取选中的内容的坐标,结合固定定位确定选项按钮的位置
    const temNode = document.getElementById("tem");
    temNode.style.display = "none";
    // 选中内容不存在或空,不弹出按钮选项
    if (selectionText) {
      console.log("您选中了:" + selectionText);
      temNode.style.display = "block";
      temNode.style.top = e.y + 20 + "px";
      temNode.style.left = e.x + "px";
    }
  }

  // 复制内容到剪切板逻辑
  function clickCopy() {
    window.getSelection().toString();
    console.log("您点击了复制");
  }

  // 翻译功能逻辑
  function clickTranslate() {
    console.log("您点击了翻译");
  }

  // 拨打电话逻辑
  function clickTel() {
    console.log("您点击了拨打");
  }
</script>
</body>
</html>