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防止网站被扒的解决方法

    这个代码能够直接保护整个站,而不再是单个页面,直接把代码放到自己的网站上,如果是博客建议放到header.php头部...

    js教程 27分钟前
  • Hexo插件开发实战教程

    Hexo的插件嵌入有两种方式,一种是通过脚本(Scripts)的方式引入,一种是通过插件(Packages)的方式将自定义的插件内...

    js教程 2周前
  • JavaScript定时删除指定元素方法

    JavaScript定时删除指定元素一般用到自动隐藏的效果功能上面,主要用到了JS的setTimeout语法。下面是一个定时...

    js教程 2周前
  • echarts增加loading加载中效果方法

    需要开发echarts中的loading加载中效果,我们可以使用到echart自带showLoading()方法。在需要加载数据的地方...

    js教程 4周前
  • js如何获取指定网址中的参数

    之前我的站长站分享的都是用JS获取当前网址URL中的参数,我们这次教大家如何获取指定网址中的参数。js获取网...

    js教程 4周前