zoukankan      html  css  js  c++  java
  • 把页面某内容放入粘贴板中

    在很多的网站,相信大家都有看到,点击一个按钮之后,就把对应的代码或者地址放置到了粘贴板中,这种操作粘贴板的方法是什么呢,下面就来跟大家分享一下;

     1 function copyToClipboard(elem) {
     2 // create hidden text element, if it doesn't already exist
     3 var targetId = "_hiddenCopyText_";
     4 var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
     5 var origSelectionStart, origSelectionEnd;
     6 if (isInput) {
     7 // can just use the original source element for the selection and copy
     8 target = elem;
     9 origSelectionStart = elem.selectionStart;
    10 origSelectionEnd = elem.selectionEnd;
    11 } else {
    12 // must use a temporary form element for the selection and copy
    13 target = document.getElementById(targetId);
    14 if (!target) {
    15 var target = document.createElement("textarea");
    16 target.style.position = "absolute";
    17 target.style.left = "-9999px";
    18 target.style.top = "0";
    19 target.id = targetId;
    20 document.body.appendChild(target);
    21 }
    22 target.textContent = elem.textContent;
    23 }
    24 // select the content
    25 var currentFocus = document.activeElement;
    26 target.focus();
    27 target.setSelectionRange(0, target.value.length);
    28 // copy the selection
    29 var succeed;
    30 try {
    31 succeed = document.execCommand("copy");
    32 } catch(e) {
    33 succeed = false;
    34 }
    35 // restore original focus
    36 if (currentFocus && typeof currentFocus.focus === "function") {
    37 currentFocus.focus();
    38 }
    39 if (isInput) {
    40 // restore prior selection
    41 elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    42 } else {
    43 // clear temporary content
    44 target.textContent = "";
    45 }
    46 return succeed;
    47 }
    48 
    49 //调用
    50 copyToClipboard(document.getElementById("name"));//这里传入的参数是要把哪一个标签里面的内容使用,就放入哪个元素即可;

    操作系统的东西,当然要原生的js兼容性更好了赛;看起来还是很方便吧!

  • 相关阅读:
    idea中svn代码冲突
    数据库表的连接(Left join , Right Join, Inner Join)用法详解
    @Param注解的用法解析
    spring @Transactional注解参数详解
    数据库的DDL、DML和DCL的区别与理解
    Mybatis:resultMap的使用总结
    Maps.newHashMap 和 new HashMap的区别
    php 个推的例子
    fidder 调接口 的 小常识
    php Memcached
  • 原文地址:https://www.cnblogs.com/cj28-27/p/6372631.html
Copyright © 2011-2022 走看看