11人参与 • 2025-02-14 • Javascript
点击“复制”按钮,获取当前点击事件的父级元素(id="block")下子元素(id="texttocopy")下的文本
<div class="chats"> <div class="block"> <div class="layui-col-xs12 layui-col-sm12 layui-col-md12" style="width: 90%; margin: 0.2rem auto; box-sizing:border-box; display:flex;flex-direction:row;"> <!-- 省略部分代码 --> <div id="texttocopy" style="flex: 0.9; line-height: 0.45rem; margin: 0 0.1rem; background: #f5f5f5; padding: 0.1rem; border-radius:5px"> <p>hello! it seems like you've entered a string of "nnnn." if you have any questions or need assistance</p> </div> </div> <div class="layui-col-xs12 layui-col-sm12 layui-col-md12"> <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" class="copy-link">复制</a> </div> </div> <div class="block"> <div class="layui-col-xs12 layui-col-sm12 layui-col-md12" style="width: 90%; margin: 0.2rem auto; box-sizing:border-box; display:flex;flex-direction:row;"> <!-- 省略部分代码 --> <div id="texttocopy" style="flex: 0.9; line-height: 0.45rem; margin: 0 0.1rem; background: #f5f5f5; padding: 0.1rem; border-radius:5px"> <p>hello! please feel free to ask, and i'll be happy to help.</p> </div> </div> <div class="layui-col-xs12 layui-col-sm12 layui-col-md12"> <a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" class="copy-link">复制</a> </div> </div> </div>
document.addeventlistener('domcontentloaded', function() { // 为所有 .block 的父元素添加点击事件监听,使用事件委托处理 .copy-link 的点击 document.queryselector('.chats').addeventlistener('click', function(e) { // 检查点击的元素是否是我们想要的 .copy-link if (e.target.matches('.copy-link')) { // 找到点击的 .copy-link 所在的 .block var block = e.target.closest('.block'); // 在 .block 中找到 #texttocopy(注意:id应唯一,这里仅为示例) var texttocopy = block.queryselector('#texttocopy p'); // 获取文本内容 var text = texttocopy.textcontent || texttocopy.innertext; // console.log(text) // 使用navigator.clipboard api进行复制(现代浏览器) if (navigator.clipboard) { navigator.clipboard.writetext(text).then(function() { console.log('复制成功'); }, function(err) { console.error('复制失败:', err); }); } else { // 对于不支持clipboard api的浏览器,可以使用旧方法(例如创建一个临时的textarea) var textarea = document.createelement('textarea'); textarea.value = text; document.body.appendchild(textarea); textarea.select(); document.execcommand('copy'); document.body.removechild(textarea); console.log('已复制到剪贴板'); } } }); });
到此这篇关于前端jquery复制文本到剪贴板功能实现的文章就介绍到这了,更多相关jq复制文本到剪贴板内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论