Как скопировать текст в буфер обмена HTML? - PullRequest
0 голосов
/ 25 апреля 2020

У меня есть элемент set p, который содержит ссылку. Я хотел бы, чтобы пользователь нажал кнопку, и он получил значение элемента p и скопировал его в буфер обмена пользователя.

function copy() {
  document.getElementById("link").copy;
}
#link {
  color: blue;
}
<p id="link" onclick="copy()">https://www.spotify.com/us/</p>

Ответы [ 3 ]

1 голос
/ 25 апреля 2020

function copy() {
  var copyText = document.getElementById("link").innerText;
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = copyText;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  alert("Copied the text");
}
#link {
  color: blue;
}
<p id="link" onclick="copy()">https://www.spotify.com/us/</p>

Ваша функция копирования может быть следующей

function copy() {
  var copyText = document.getElementById("link").innerText;
  var elem = document.createElement("textarea");
  document.body.appendChild(elem);
  elem.value = copyText;
  elem.select();
  document.execCommand("copy");
  document.body.removeChild(elem);
  alert("Copied the text");
}
0 голосов
/ 25 апреля 2020

вы можете использовать input для копирования текста в буфер обмена

function copy() {
    /* Get the text field */
    var copyText = document.getElementById("link");

    /* Select the text field */
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/

    /* Copy the text inside the text field */
    document.execCommand("copy");
    console.log("copied!");
}
<input id="link" onclick="copy()" value="https://www.spotify.com/us/">

Или, если вы хотите использовать p, вы можете использовать этот трюк

function copy() {
    /* Get the text field */
    var copyText = document.getElementById("link");
    var copyP = document.getElementById("link_p");
    copyText.value=copyP.innerHTML;

    /* Select the text field */
    copyText.select();
    copyText.setSelectionRange(0, 99999); /*For mobile devices*/

    /* Copy the text inside the text field */
    document.execCommand("copy");
    console.log("copied!");
}
<input type="text" id="link" value="" style="display:none">
<p id="link_p" onclick="copy()">text</p>
0 голосов
/ 25 апреля 2020

попробуйте это как функцию копирования

var text =  document.getElementById("link");
text.select();
document.execCommand("copy);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...