栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

单击按钮使用jQuery复制到剪贴板

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

单击按钮使用jQuery复制到剪贴板

编辑

自2016年起,您现在可以在大多数浏览器中将文本复制到剪贴板,因为大多数浏览器都可以通过编程方式将选择的文本复制到剪贴板

document.execCommand("copy")
,从而可以将所选内容关闭。

与浏览器中的某些其他操作(如打开新窗口)一样,只能通过特定的用户操作(如单击鼠标)将内容复制到剪贴板。例如,它不能通过计时器来完成。

这是一个代码示例:

document.getElementById("copyButton").addEventListener("click", function() {    copyToClipboard(document.getElementById("copyTarget"));});function copyToClipboard(elem) {      // create hidden text element, if it doesn't already exist    var targetId = "_hiddenCopyText_";    var isInput = elem.tagName === "INPUT" || elem.tagName === "textarea";    var origSelectionStart, origSelectionEnd;    if (isInput) {        // can just use the original source element for the selection and copy        target = elem;        origSelectionStart = elem.selectionStart;        origSelectionEnd = elem.selectionEnd;    } else {        // must use a temporary form element for the selection and copy        target = document.getElementById(targetId);        if (!target) { var target = document.createElement("textarea"); target.style.position = "absolute"; target.style.left = "-9999px"; target.style.top = "0"; target.id = targetId; document.body.appendChild(target);        }        target.textContent = elem.textContent;    }    // select the content    var currentFocus = document.activeElement;    target.focus();    target.setSelectionRange(0, target.value.length);    // copy the selection    var succeed;    try {          succeed = document.execCommand("copy");    } catch(e) {        succeed = false;    }    // restore original focus    if (currentFocus && typeof currentFocus.focus === "function") {        currentFocus.focus();    }    if (isInput) {        // restore prior selection        elem.setSelectionRange(origSelectionStart, origSelectionEnd);    } else {        // clear temporary content        target.textContent = "";    }    return succeed;}input {  width: 400px;}<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br><input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">

答案的历史部分

出于安全原因,任何现代浏览器均不允许通过Javascript直接复制到剪贴板。最常见的解决方法是使用Flash功能将其复制到剪贴板,这只能由用户直接单击触发。

如前所述,ZeroClipboard是用于管理Flash对象进行复制的常用代码集。我用过了如果在浏览设备上安装了Flash(排除了移动设备或平板电脑),则它可以工作。


下一个最常见的解决方法是将剪贴板上的文本放置在输入字段中,将焦点移到该字段上,并建议用户按

Ctrl
+
C
复制文本。

Internet Explorer和Firefox曾经具有用于访问剪贴板的非标准API,但它们的较新版本已弃用了这些方法(可能出于安全原因)。


一项新兴的标准工作试图尝试一种“安全”的方法来解决最常见的剪贴板问题(可能需要像Flash解决方案所要求的那样的特定用户操作),并且看起来它可能是在最新版本中部分实现的版本的Firefox和Chrome,但我尚未确认。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/416137.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号