如何获得按钮来复制某些内容?

时间:2017-04-21 11:39:50

标签: javascript html css

<input value="hello" id="p1" readonly style="width: 100%;">
    <br><p>
        <div class="btn-main">Copy!</div>

当访客按下班级&#34; btn-main&#34;我希望将输入值复制到剪贴板。

3 个答案:

答案 0 :(得分:0)

&#13;
&#13;
function copyToClipboard(text) {
    window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
  }
&#13;
<button id="demo-btn" onclick="copyToClipboard(document.getElementById('demo-btn').innerHTML)">Copy!</button>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以使用jQuery clone() Method

描述: - clone()方法复制了所选元素,包括子节点,文本和属性。

$(document).ready(function(){
    $("button").click(function(){
        $("p").clone().appendTo("body");
    });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

<button>Clone all p elements, and append them to the body element</button>

</body>
</html>

答案 2 :(得分:0)

也可以这样做,

&#13;
&#13;
document.getElementById("copyBtn").addEventListener("click", function() {
  target = document.getElementById("p1");
  target.focus()
  target.setSelectionRange(0, target.value.length);
  document.execCommand('copy');
});
&#13;
<input value="hello" id="p1" style="width: 100%;">
<br>
<p>
  <button id="copyBtn" class="btn-main">Copy!</button>

  <textarea></textarea>
  <p> Press Ctrl + V in the text area to see the copied text</p>
&#13;
&#13;
&#13;