如何实现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 内容,请继续关注web建站教程。
当前网址:https://ipkd.cn/webs_2334.html
workflows工作流
一只由水晶制成的蜂鸟
一种长着彩虹翅膀的虫子comfyui工作流
树枝上一只色彩斑斓的小鸟
Latent放大comfyui工作流
泰坦尼克号桌面壁纸上ComfyUI工作流
一张皮卡丘向观众眨眼的逼真照片ComfyUI工作流
图生图工作流:藏族姑娘ComfyUI工作流
一只可爱的草莓味冰淇淋卷筒
猜你喜欢
声明:本站提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请发送到邮箱:admin@ipkd.cn,我们会在看到邮件的第一时间内为您处理!

利用js+css3做一个小鱼游泳特效
用svg画出游泳池动画效果
css3绘制一个会动的大嘴鸟
jquery鼠标滑过图片边框特效(jquery.focus-follow插件)
用ascii字符画图像
Bootstrap可视化拖放布局
2023年程序猿如何给自己开启一场烟花盛会
javascript如何利用draggable实现一个拖拽效果











