3

JavaScript 点击按钮一键复制指定文本内容

 9 months ago
source link: https://yjyj.net/css/6419.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

JavaScript 点击按钮一键复制指定文本内容

2023-07-27 4 0

navigator.clipboard.writeText('message')

该方法更为简单实用,且兼容性好,废话不多说,直接上代码:

<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <div class="message">这段文本将被复制</div> <button class="btn">点击复制</button> <script> const copyEl = document.querySelector('.message') const btnEl = document.querySelector('.btn') btnEl.addEventListener('click', () => { // 该方法可以写入特定字符串到操作系统的剪切板,并返回一个Promise // 一旦剪贴板的内容被更新,它就会被解析。如果调用者没有写入剪贴板的权限,则拒绝写入剪切板(reject) navigator.clipboard .writeText(copyEl.textContent) .then(() => { console.log('复制成功') }) .catch(() => { console.log('复制失败') }) }) </script> </body></html>

该方法可以写入特定字符串到操作系统的剪切板,并返回一个Promise,复制成功调用resolve,复制失败调用reject,比方法一更方便快捷。选他就完事了。

Via. https://www.jianshu.com/p/601f6d4683bd


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK