请你看一下这个演示,让我知道为什么当我尝试从#coordinateX
调用复制功能来读取按钮文本时,我无法复制#map
值#coordinateX
但代码适用于输入文本?
如何才能使它能够读取按钮值?
(function() {
'use strict';
// click events
document.body.addEventListener('click', copy, true);
// event handler
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');
}
}
}
})();
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>
答案 0 :(得分: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!';
}
});
Fiddler https://jsfiddle.net/ktgzujLe/