亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JS復(fù)制對應(yīng)id的內(nèi)容到粘貼板(Ctrl+C效果)

 更新時(shí)間:2017年01月23日 14:53:16   作者:鍋?zhàn)硬┛? 
這篇文章主要給大家介紹了利用JS實(shí)現(xiàn)復(fù)制指定對應(yīng)id的內(nèi)容到粘貼板(Ctrl+C效果),文中給出了詳細(xì)的介紹和示例代碼,有需要的朋友可以參考借鑒,下面來一起看看吧。

前言

最近在做一個(gè)按鈕,實(shí)現(xiàn)的效果是當(dāng)點(diǎn)擊后復(fù)制url到黏貼板,但不是當(dāng)前頁面url,而是對應(yīng)一個(gè)元素的url,且一個(gè)頁面會(huì)有多個(gè)url。一開始找到一個(gè)方法,但是竟然只兼容IE瀏覽器,神奇了,竟然有只兼容IE的東西。后來發(fā)現(xiàn)一個(gè)zeroclipboard.js這個(gè)插件,但是怎么也搞不出那個(gè)效果,有點(diǎn)麻煩。

最后翻到了一個(gè)js封裝好的方法,有效!

想要實(shí)現(xiàn)的一個(gè)效果是,下面html代碼:

<tr>
 <td>
 <a id="copy_{$key}" onclick="getUrl('{$key}')">復(fù)制文件鏈接</a>
 <input id="file_{$key}" value="{$file.file_url}" style="margin-left: -9999px"/>
 </td>
</tr> 

點(diǎn)擊復(fù)制文件鏈接這個(gè)按鈕,復(fù)制input框里的value值,是傳進(jìn)去的一個(gè)url;首先點(diǎn)擊a標(biāo)簽會(huì)觸發(fā)getUrl這個(gè)函數(shù);傳進(jìn)去id用于找到對應(yīng)的input然后取值(因?yàn)楸闅v了多個(gè)td,有許多個(gè)input框一一對應(yīng)去?。?/p>

下面js代碼:

<pre><script type="application/javascript">
 
 function getUrl(id) {
  if (copyToClipboard(document.getElementById("file_"+id))){
   alert("成功復(fù)制到黏貼板!");
  }else{
   alert("復(fù)制到黏貼板失敗!");
  }
 }
 
 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中調(diào)用了封裝好的copyToClipboard方法實(shí)現(xiàn)了功能。有一點(diǎn)的是html中input的樣式用style="margin-left: -9999px"進(jìn)行隱藏,因?yàn)椴恢罏槭裁从胻ype="hiden"或者display="none"去隱藏都只會(huì)獲取源代碼而不是動(dòng)態(tài)的url遍歷出來的值。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。

相關(guān)文章

最新評論