我在创建一个功能时遇到问题,该功能允许某人点击不同的按钮并选择相应的<p>
标签,然后将所述<p>
标签内的文字复制到剪贴板要粘贴。
<p class="copyableInput grey49" id="p7">#494949</p>
<button class="copyableInputButton" onclick="copyToClipboard(p7)">COPY #
</button>
<p class="copyableInput grey66" id="p8">#666666</p>
<button class="copyableInputButton" onclick="copyToClipboard(p8)">COPY #
</button>
<p class="copyableInput greycc" id="p9">#cccccc</p>
<button class="copyableInputButton" onclick="copyToClipboard(p9)">COPY #
</button>
<p class="copyableInput greyf9" id="p10"><span
style="color:#494949">#f9f9f9</span></p>
<button class="copyableInputButton" onclick="copyToClipboard(p10)">COPY #
</button>
function copyToClipboard(target){
var copy= document.getElementById(target);
copy.select();
document.execCommand("Copy");
alert("Copied the text: " + copy.value);
}
https://jsfiddle.net/gchis66/xrtLfffh/1/
如果我忘记了某件事,请告诉我。
答案 0 :(得分:1)
当您单击该按钮时,该函数将获取段落标记:
<p id="p9" class="copyableInput greycc">
所以你必须检查这样的内容:
var copy = target.innerHTML
答案 1 :(得分:1)
此功能适用于更多浏览器。
请参阅此JSFiddle
<p class="copyableInput grey49" id="p7">#494949</p>
<button class="copyableInputButton" onclick="copyToClipboard('p7')">COPY #</button>
<p class="copyableInput grey66" id="p8">#666666</p>
<button class="copyableInputButton" onclick="copyToClipboard('p8')">COPY #</button>
<p class="copyableInput greycc" id="p9">#cccccc</p>
<button class="copyableInputButton" onclick="copyToClipboard('p9')">COPY #</button>
<p class="copyableInput greyf9" id="p10"><span style="color:#494949">#f9f9f9</span></p>
<button class="copyableInputButton" onclick="copyToClipboard('p10')">COPY #</button>
function copyToClipboard(target) {
var element = document.getElementById(target);
var text = element.innerHTML;
CopyToClipboard(text);
alert("Copied the text");
}
function CopyToClipboard (text) {
// Copies a string to the clipboard. Must be called from within an
// event handler such as click. May return false if it failed, but
// this is not always possible. Browser support for Chrome 43+,
// Firefox 42+, Safari 10+, Edge and IE 10+.
// IE: The clipboard feature may be disabled by an administrator. By
// default a prompt is shown the first time the clipboard is
// used (per session).
if (window.clipboardData && window.clipboardData.setData) {
// IE specific code path to prevent textarea being shown while dialog is visible.
return clipboardData.setData("Text", text);
} else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
var textarea = document.createElement("textarea");
textarea.textContent = text;
textarea.style.position = "fixed"; // Prevent scrolling to bottom of page in MS Edge.
document.body.appendChild(textarea);
textarea.select();
try {
return document.execCommand("copy"); // Security exception may be thrown by some browsers.
} catch (ex) {
console.warn("Copy to clipboard failed.", ex);
return false;
} finally {
document.body.removeChild(textarea);
}
}
}