2017-03-24 87 views
0

您可以看看這個演示,並讓我知道爲什麼我不能複製#coordinateX值,當我嘗試從#map調用複製功能來從按鈕文本中讀取#coordinateX但代碼對輸入文本正常工作? 我該如何使它能夠讀取按鈕的值?從按鈕值複製到剪貼板的問題

(function() { 
 

 
\t 'use strict'; 
 
    
 
    // click events 
 
    document.body.addEventListener('click', copy, true); 
 

 
\t // event handler 
 
\t function copy(e) { 
 

 
    // find target element 
 

 
    var t = e.target; 
 

 
     var c = t.dataset.copytarget; 
 
     var inp = (c ? document.querySelector(c) : null); 
 
     
 
    // is element selectable? 
 
    if (inp && inp.select) { 
 
     
 
     // select text 
 
     inp.select(); 
 

 
     try { 
 
     // copy text 
 
     document.execCommand('copy'); 
 
     inp.blur(); 
 
     
 
     // copied animation 
 
     t.classList.add('copied'); 
 
     setTimeout(function() { t.classList.remove('copied'); }, 1500); 
 
     } 
 
     catch (err) { 
 
     alert('please press Ctrl/Cmd+C to copy'); 
 
     } 
 
     
 
    } 
 
    
 
\t } 
 

 
})();
http://www.sitepoint.com/
<div class="container"> 
 
<div class="btn-group"> 
 
    <button class="btn" id="coordinateX">49.124545</button> 
 
    <button class="btn" id="map" data-copytarget="#coordinateX">Copy Coordinate</button> 
 
</div> 
 

 
<br /> 
 
    <label for="website">Website:</label> 
 
<input type="text" id="txtCoordinateX" value="49.124545" /> 
 
<button data-copytarget="#txtCoordinateX">Copy Coordinate From Input</button> 
 

 

 
</div>

+1

複製適用於只是用戶可編輯的文本。這是我輸入的標籤(帶有文本框)和contentEditable dom元素。在該按鈕上打一個contenteditable = true屬性以便快速修復。 –

+0

感謝您的回覆,但仍然無法正常工作 – Behseini

回答

1
<div class="container"> 
<div class="btn-group"> 
    <button class="btn" id="coordinateX">49.124545</button> 
    <button class="btn" id="map" data-copytarget="#coordinateX">Copy Coordinate</button> 
</div> 

<br /> 
    <label for="website">Website:</label> 
<input type="text" id="txtCoordinateX" value="49.124545" /> 
<button data-copytarget="#txtCoordinateX" id="copyBlock">Copy Coordinate From Input</button> 

<span id="copyAnswer"></span> 
</div> 

var textarea = document.getElementById("txtCoordinateX"); 
var answer = document.getElementById("copyAnswer"); 
var copy = document.getElementById("copyBlock"); 
copy.addEventListener('click', function(e) { 

    // Select some text (you could also create a range) 
    textarea.select(); 

    // Use try & catch for unsupported browser 
    try { 

     // The important part (copy selected text) 
     var successful = document.execCommand('copy'); 

     if(successful) answer.innerHTML = 'Copied!'; 
     else answer.innerHTML = 'Unable to copy!'; 
    } catch (err) { 
     answer.innerHTML = 'Unsupported Browser!'; 
    } 
}); 

提琴手https://jsfiddle.net/ktgzujLe/