web建站教程
  1. 首页
  2. vuejs
  3. js
  4. 好玩
  5. seo教程
  6. 前端知识
  7. 百度echarts
  8. 更多
    php入门
    nodejs
    mockjs
    reactjs
    mysql
    wordpress
    织梦cms
    帝国cms
    git教程
    IT知识
    模板大全
    休息站

js如何实现复制页面内容的三种方法

878 ℃
     

如何实现div内容的复制?下面web建站小编给大家介绍三种内容复制的方法。

1、利用Async Clipboard API实现

const promise = navigator.clipboard.writeText(newClipText);
//需要注意,方法的返回值是个 Promise。并且使用此方法时,页面必须处于 focus 状态,否则会报错。

2、覆写 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();
});

3、利用Document.execCommand API实现

<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);
    }
  }
});

javscript获取本月的开始日期和结束日期(包括上个月、下个月)

js监听浏览器刷新及关闭(第一次进入)

js实现对象for循环遍历赋值

js创建一个指定长度数组(根据数字显示数组长度)

js两个数组是否存在重复的元素

标签: addEventList, js, 复制, 复制页面内容

上面是“js如何实现复制页面内容的三种方法”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。

当前网址:https://ipkd.cn/webs_2334.html

声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

当前位置: 网站首页 > js
本文共计1741个字,预计阅读时长12分钟
生活小工具,收录了80多款小工具
上一篇: 推荐2款充满科技感的艺术字体——小新黑体、小新潮酷体
下一篇: 推荐一款浏览器数据库的开源工具库——Dexie.js(JavaScript调用)
x 打工人ai神器