觐有 发表于 2026-2-9 20:05:07

用户单击文本并复制至剪帖板

Html5网页,一些内容,可以让用户点击选中文本,并把选中的文本复制至剪帖板(Clipboard)。
Insus.NET已经实现与测试,记录于此,方便时可以重来查阅与参考。

复制文本到剪贴板(兼容所有浏览器)
https://img2024.cnblogs.com/blog/28036/202601/28036-20260126144012196-2009736584.jpg 
https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttps://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.giffunction CopyTextToClipboard(text) {    // 方法1: 使用现代Clipboard API(首选)    if (navigator.clipboard && window.isSecureContext) {      return navigator.clipboard.writeText(text)            .then(() => {                return true;            })            .catch(err => {                return FallbackCopyTextToClipboard(text);            });    }    else {      return FallbackCopyTextToClipboard(text);    }}View Code 
备用复制方法:
https://img2024.cnblogs.com/blog/28036/202601/28036-20260126144417821-2120075038.jpg

https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttps://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.giffunction FallbackCopyTextToClipboard(text) {    return new Promise((resolve, reject) => {      const textArea = document.createElement('textarea');      // 设置样式确保不可见但可选中      textArea.style.position = 'fixed';      textArea.style.top = '0';      textArea.style.left = '0';      textArea.style.width = '2em';      textArea.style.height = '2em';      textArea.style.padding = '0';      textArea.style.border = 'none';      textArea.style.outline = 'none';      textArea.style.boxShadow = 'none';      textArea.style.background = 'transparent';      textArea.style.opacity = '0';      textArea.value = text;      document.body.appendChild(textArea);      // 选中文本      textArea.select();      textArea.setSelectionRange(0, textArea.value.length);      try {            // 尝试执行复制命令            const successful = document.execCommand('copy');            document.body.removeChild(textArea);            if (successful) {                resolve(true);            } else {                reject(new Error('复制失败'));            }      } catch (err) {            document.body.removeChild(textArea);            reject(err);      }    });}View Code 
选中元素内的文本(跨浏览器兼容)
https://img2024.cnblogs.com/blog/28036/202602/28036-20260208131501070-466372182.png
 
https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttps://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.giffunction SelectText(element) {    // 如果元素本身是input或textarea,直接选中    if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {      element.select();      return;    }    var sel, range;    // 现代浏览器    if (window.getSelection && document.createRange) {      sel = window.getSelection();      if (sel.toString() === '') { // 如果没有已选中的文本            window.setTimeout(function () {                range = document.createRange();                range.selectNodeContents(element);                sel.removeAllRanges();                sel.addRange(range);            }, 1);      }    }    // IE 8及以下    else if (document.selection) {      sel = document.selection.createRange();      if (sel.text === '') {            range = document.body.createTextRange();            range.moveToElementText(element);            range.select();      }    }}View Code 
增强版单击复制函数,同时复制并选中
https://img2024.cnblogs.com/blog/28036/202602/28036-20260208143503862-263760795.png
 
https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttps://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.giffunction CopyAndSelect(element) {    // 获取要复制的文本    let textToCopy = '';    // 根据元素类型获取文本    if (element.tagName === 'INPUT' || element.tagName === 'TEXTAREA') {      textToCopy = element.value;    } else {      textToCopy = element.innerText || element.textContent;    }    // 清理文本(去除首尾空格)    textToCopy = textToCopy.trim();    // 如果有自定义属性,优先使用    if (element.dataset.copyValue) {      textToCopy = element.dataset.copyValue;    }    // 复制文本到剪贴板    CopyTextToClipboard(textToCopy).then(success => {      if (success) {            // 选中元素文本(视觉反馈)            SelectText(element);            // 可选:添加视觉反馈样式            element.classList.add('copied');            setTimeout(() => {                element.classList.remove('copied');            }, 1000);      }    }).catch(err => {      console.error('复制失败:', err);      // 即使复制失败,也选中文本让用户可以手动复制      SelectText(element);    });}View Code 
把以上几个函数集合一起,另存成一个js脚本文件,在需要的地址,引用即可。
当然,你觉得有需要优化与修改的地方自行修改或者让Insus.NET知道。

下面写个示例:
样式,
https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttps://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif   .click-to-copy {      cursor: pointer;    }      .click-to-copy:hover {            background-color: #f0f8ff;            border-color: #1890ff;      }View Code
html,
https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttps://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif单击复制示例

                                                  ITEM-2026-301-663-237                                                    ITEM 2026 301 663 237                                                    PO-2026/01-001-A                                                    显示文本:SPECIAL CODE 123 456                                                                      物料编码                  描述                                                  MAT-001-2024                  螺丝刀                                                  MAT-002-2024                  扳手                                                              View Code 
引用jquery和js脚本,
                        
javascript,
https://img2024.cnblogs.com/blog/28036/202602/28036-20260208164914147-1808205735.png
 
https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gifhttps://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif $(document).ready(function () {   $(".click-to-copy").click(function (e) {         // 防止事件冒泡到父元素         e.stopPropagation();         // 获取要复制的文本         var textToCopy = $(this).data('copy-value') || $(this).text().trim();         // 复制到剪贴板         CopyTextToClipboard(textToCopy).then(function (success) {             if (success) {               // 选中文本(视觉反馈)               SelectText(this);               // 添加视觉反馈               $(this).addClass('copied');               setTimeout(function () {                     $(this).removeClass('copied');               }.bind(this), 1000);             }         }.bind(this)).catch(function (err) {             console.error('复制失败:', err);             // 即使复制失败也选中文本             SelectText(this);         }.bind(this));   }); });View Code 
操作演示,
https://img2024.cnblogs.com/blog/28036/202602/28036-20260209112625440-1202711184.gif
 
再做一个简单示例,
https://img2024.cnblogs.com/blog/28036/202602/28036-20260209113630168-2116341470.png
 
非纯javascript实现,得结合jquery一起。


 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

育局糊 发表于 7 天前

过来提前占个楼

闻成 发表于 7 天前

新版吗?好像是停更了吧。

栓州 发表于 7 天前

收藏一下   不知道什么时候能用到

寇秀娟 发表于 6 天前

谢谢分享,试用一下

芮梦月 发表于 12 小时前

喜欢鼓捣这些软件,现在用得少,谢谢分享!
页: [1]
查看完整版本: 用户单击文本并复制至剪帖板