这里有新鲜出炉的 Javascript 教程,程序狗速度看过来!
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
这篇文章主要给大家介绍了利用 JS 实现复制指定对应 id 的内容到粘贴板(Ctrl+C 效果), 文中给出了详细的介绍和示例代码,有需要的朋友可以参考借鉴,下面来一起看看吧。
前言
最近在做一个按钮,实现的效果是当点击后复制 url 到黏贴板,但不是当前页面 url,而是对应一个元素的 url,且一个页面会有多个 url。一开始找到一个方法,但是竟然只兼容 IE 浏览器,神奇了,竟然有只兼容 IE 的东西。后来发现一个 zeroclipboard.js 这个插件,但是怎么也搞不出那个效果,有点麻烦。
最后翻到了一个 js 封装好的方法,有效!
想要实现的一个效果是,下面 html 代码:
- <tr>
- <td>
- <a id="copy_{$key}" onclick="getUrl('{$key}')">
- 复制文件链接
- </a>
- <input id="file_{$key}" value="{$file.file_url}" style="margin-left: -9999px"
- />
- </td>
- </tr>
点击复制文件链接这个按钮,复制 input 框里的 value 值,是传进去的一个 url;首先点击 a 标签会触发 getUrl 这个函数;传进去 id 用于找到对应的 input 然后取值(因为遍历了多个 td,有许多个 input 框一一对应去取)。
下面 js 代码:
- <pre>
- <script type="application/javascript">
- function getUrl(id) {
- if (copyToClipboard(document.getElementById("file_" + id))) {
- alert("成功复制到黏贴板!");
- } else {
- alert("复制到黏贴板失败!");
- }
- }
- 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;
- }
- </script>
- </pre>
getUrl 中调用了封装好的 copyToClipboard 方法实现了功能。有一点的是 html 中 input 的样式用 style="margin-left: -9999px" 进行隐藏,因为不知道为什么用 type="hiden" 或者 display="none" 去隐藏都只会获取源代码而不是动态的 url 遍历出来的值。
总结
来源: http://www.phperz.com/article/17/0601/328167.html