js教程

js复制网页内容教程

我的站长站 2024-01-03 人阅读

Async Clipboard API方法

HTML5新增的方法,无需引入第三方插件,直接就可以复制内容。低版本的浏览器可能会不兼容。

const promise = navigator.clipboard.writeText(newClipText);

方法的返回值是个 Promise。并且使用此方法时,页面必须处于 focus 状态,否则会报错。

覆写copy 事件方法

// Overwrite what is being copied to the clipboard.
document.addEventListener('copy', function (e) {
  // e.clipboardData is initially empty, but we can set it to the
  // data that we want copied onto the clipboard.
  e.clipboardData.setData('text/plain', '西炒蛋');
  // This is necessary to prevent the current document selection from
  // being written to the clipboard.
  e.preventDefault();
});

Document.execCommandAPI方法

<p id="content">123456</p>
<button id="copyButton">复制</button>

复制div元素内容

const copyButton = document.getElementById('copyButton');
const content = document.getElementById('content');
copyButton.addEventListener('click', function () {
  const selection = window.getSelection();
  const range = document.createRange();
  // 缓存用户选中的内容
  const currentRange =
    selection.rangeCount === 0 ? null : selection.getRangeAt(0);
  // 设置文档片段
  range.selectNodeContents(content);
  // 清空选中内容
  selection.removeAllRanges();
  // 将文档片段设置为选中内容
  selection.addRange(range);
  try {
    // 复制到剪贴板
    document.execCommand('copy');
  } catch (err) {
    // 提示复制失败
  } finally {
    selection.removeAllRanges();
    if (currentRange) {
      // 还原用户选中内容
      selection.addRange(currentRange);
    }
  }
});

复制input元素内容

const copyButton = document.getElementById('copyButton');
const inputEl = document.getElementById('input');
copyButton.addEventListener('click', function () {
  const selection = window.getSelection();
  const currentRange =
    selection.rangeCount === 0 ? null : selection.getRangeAt(0);
  // 选中 input 内容
  inputEl.select();
  // 复制到剪贴板
  try {
    document.execCommand('copy');
  } catch (err) {
    // 提示复制失败
    // 。。。
  } finally {
    selection.removeAllRanges();
    if (currentRange) {
      // 还原用户选中内容
      selection.addRange(currentRange);
    }
  }
});


最新更新
  • js截取字符串教程

    slice()方法接受两个参数,起始索引和结束索引(可选)。它返回从起始索引到结束索引(不包括结束索引)之间的子字符...

    js教程 2个月前
  • find findIndex indexOf索引选择器使用方法

    find使用方法find方法是ES6引入的一种数组方法,可以用来查找数组中符合条件的元素。语法是:array.find(callba...

    js教程 3个月前
  • js复制网页内容教程

    Async Clipboard API方法HTML5新增的方法,无需引入第三方插件,直接就可以复制内容。低版本的浏览器可能会不兼...

    js教程 3个月前
  • js获取字符长度函数分享

    js获取字符长度函数function objLen(str) { if (str == null) return 0; if (typeof str != "string") { ...

    js教程 3个月前
  • 网站LED跑马灯效果广告代码

    网站可以看到很多的论坛网站都会用到这种网站LED跑马灯效果,这种效果实现也很简单,分享给大家。LED跑马灯效果...

    js教程 4个月前