
如何实现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获取本月的开始日期和结束日期(包括上个月、下个月)
标签: addEventList, js, 复制, 复制页面内容
上面是“js如何实现复制页面内容的三种方法”的全面内容,想了解更多关于 js 内容,请继续关注web建站教程。
当前网址:https://m.ipkd.cn/webs_2334.html
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

帝国cms给列表页模板里推荐信息添加图标代码