Нажмите кнопку скопировать в буфер обмена с помощью jQuery

Как мне скопировать текст внутри div в буфер обмена? У меня есть div и мне нужно добавить ссылку, которая добавит текст в буфер обмена. Есть ли решение для этого?

<p class="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>

<a class="copy-text">copy Text</a>

После того, как я нажму кнопку "Скопировать текст", я нажимаю Ctrl + V, его необходимо вставить.

34 ответа

Решение

Редактировать с 2016 года

С 2016 года вы теперь можете копировать текст в буфер обмена в большинстве браузеров, потому что большинство браузеров имеют возможность программно копировать выделенный текст в буфер обмена, используя document.execCommand("copy") это работает от выбора.

Как и в случае некоторых других действий в браузере (например, открытие нового окна), копирование в буфер обмена может быть выполнено только с помощью определенного действия пользователя (например, щелчка мышью). Например, это нельзя сделать с помощью таймера.

Вот пример кода:

document.getElementById("copyButton").addEventListener("click", function() {
    copyToClipboard(document.getElementById("copyTarget"));
});

function copyToClipboard(elem) {
   // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    
    // copy the selection
    var succeed;
    try {
       succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    
    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
}
input {
  width: 400px;
}
<input type="text" id="copyTarget" value="Text to Copy"> <button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">


Вот немного более продвинутая демонстрация: https://jsfiddle.net/jfriend00/v9g1x0o6/

И вы также можете получить готовую библиотеку, которая сделает это за вас с clipboard.js.


Старая, историческая часть ответа

Прямое копирование в буфер обмена с помощью JavaScript не разрешено никаким современным браузером из соображений безопасности. Наиболее распространенным обходным решением является использование возможности Flash для копирования в буфер обмена, которая может быть вызвана только прямым щелчком пользователя.

Как уже упоминалось, ZeroClipboard - это популярный набор кода для управления объектом Flash, который выполняет копирование. Я использовал это. Если Flash установлен на устройстве просмотра (которое исключает мобильный или планшет), это работает.


Следующий наиболее распространенный обходной путь - просто поместить связанный с буфером обмена текст в поле ввода, переместить фокус на это поле и посоветовать пользователю нажать Ctrl + C, чтобы скопировать текст.

Другие обсуждения проблемы и возможные обходные пути можно найти в этих предыдущих сообщениях переполнения стека:


Эти вопросы, требующие современной альтернативы использованию Flash, получили множество положительных отзывов и не дали ответов с решением (вероятно, потому что ни один не существует):


В Internet Explorer и Firefox использовались нестандартные API для доступа к буферу обмена, но в их более современных версиях эти методы устарели (возможно, по соображениям безопасности).


В зарождающихся стандартах предпринимаются попытки найти "безопасный" способ решения наиболее распространенных проблем с буфером обмена (вероятно, требующих определенных действий пользователя, таких как решение Flash), и похоже, что он может быть частично реализован в последней версии. версии Firefox и Chrome, но я еще не подтвердил это.

Есть и другой не Flash-способ (кроме API буфера обмена, упомянутого в ответе jfriend00). Вам нужно выделить текст и затем выполнить команду copy скопировать в буфер обмена любой текст, выбранный в данный момент на странице.

Например, эта функция скопирует содержимое переданного элемента в буфер обмена (обновлено с предложением в комментариях от PointZeroTwo):

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

Вот как это работает:

  1. Создает временное скрытое текстовое поле.
  2. Копирует содержимое элемента в это текстовое поле.
  3. Выбирает содержимое текстового поля.
  4. Выполняет команду copy следующим образом: document.execCommand("copy"),
  5. Удаляет временное текстовое поле.

Вы можете увидеть быстрое демо здесь:

function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('#p1')">Copy P1</button>
<button onclick="copyToClipboard('#p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />

Основная проблема заключается в том, что в настоящее время не все браузеры поддерживают эту функцию, но вы можете использовать ее в основных из:

  • Chrome 43
  • Internet Explorer 10
  • Firefox 41
  • Safari 10

Обновление 1: Это может быть достигнуто также с помощью чистого решения JavaScript (без jQuery):

function copyToClipboard(elementId) {

  // Create a "hidden" input
  var aux = document.createElement("input");

  // Assign it the value of the specified element
  aux.setAttribute("value", document.getElementById(elementId).innerHTML);

  // Append it to the body
  document.body.appendChild(aux);

  // Highlight its content
  aux.select();

  // Copy the highlighted text
  document.execCommand("copy");

  // Remove it from the body
  document.body.removeChild(aux);

}
<p id="p1">P1: I am paragraph 1</p>
<p id="p2">P2: I am a second paragraph</p>
<button onclick="copyToClipboard('p1')">Copy P1</button>
<button onclick="copyToClipboard('p2')">Copy P2</button>
<br/><br/><input type="text" placeholder="Paste here for test" />

Обратите внимание, что мы передаем идентификатор без # сейчас.

Как сообщил madzohan в комментариях ниже, в некоторых случаях возникает некоторая странная проблема с 64-битной версией Google Chrome (локальный запуск файла). Эта проблема, кажется, решена с помощью решения не-jQuery выше.

Madzohan попробовал в Safari, и решение работало, но с использованием document.execCommand('SelectAll') Вместо того, чтобы использовать .select() (как указано в чате и в комментариях ниже).

Как указывает PointZeroTwo в комментариях, код можно улучшить, чтобы он возвращал результат успеха / неудачи. Вы можете увидеть демо на этом jsFiddle.


ОБНОВЛЕНИЕ: КОПИЯ, СОХРАНЯЯ ФОРМАТ ТЕКСТА

Как указал пользователь в испанской версии Stackru, перечисленные выше решения отлично работают, если вы хотите буквально скопировать содержимое элемента, но не очень хорошо работают, если вы хотите вставить скопированный текст с форматом (как это скопировано в input type="text", формат "потерян").

Решением для этого было бы копирование в редактируемый контент div а затем скопируйте его, используя execCommand Аналогичным образом. Здесь есть пример - нажмите на кнопку копирования, а затем вставьте в поле для редактирования контента ниже:

function copy(element_id){
  var aux = document.createElement("div");
  aux.setAttribute("contentEditable", true);
  aux.innerHTML = document.getElementById(element_id).innerHTML;
  aux.setAttribute("onfocus", "document.execCommand('selectAll',false,null)"); 
  document.body.appendChild(aux);
  aux.focus();
  document.execCommand("copy");
  document.body.removeChild(aux);
}
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>

А в jQuery это было бы так:

function copy(selector){
  var $temp = $("<div>");
  $("body").append($temp);
  $temp.attr("contenteditable", true)
       .html($(selector).html()).select()
       .on("focus", function() { document.execCommand('selectAll',false,null) })
       .focus();
  document.execCommand("copy");
  $temp.remove();
}
#target {
  width:400px;
  height:100px;
  border:1px solid #ccc;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<p id="demo"><b>Bold text</b> and <u>underlined text</u>.</p>
<button onclick="copy('#demo')">Copy Keeping Format</button> 

<div id="target" contentEditable="true"></div>

С 2020 года вы должны использовать API буфера обмена.

navigator.clipboard.writeText('text here you want to copy').then(function () {
    alert('It worked! Do a CTRL - V to paste')
}, function () {
    alert('Failure to copy. Check permissions for clipboard')
});

Вот дополнительная информация о взаимодействии с буфером обмена

Простота есть основа утонченности.
Если вы не хотите, чтобы текст, который нужно скопировать, был виден:

JQuery:

$('button.copyButton').click(function(){
    $(this).siblings('input.linkToCopy').select();      
    document.execCommand("copy");
});

HTML:

<button class="copyButton">click here to copy</button>
<input class="linkToCopy" value="TEXT TO COPY"
style="position: absolute; z-index: -999; opacity: 0;"><input>

clipboard.js - хорошая утилита, которая позволяет копировать текстовые или HTML-данные в буфер обмена без использования Flash. Это очень легко использовать; просто включите.js и используйте что-то вроде этого:

<button id='markup-copy'>Copy Button</button>

<script>
    document.getElementById('markup-copy').addEventListener('click', function() {
        clipboard.copy({
            'text/plain': 'Markup text. Paste me into a rich text editor.',
            'text/html': '<i>here</i> is some <b>rich text</b>'
        }).then(
            function(){console.log('success'); },
            function(err){console.log('failure', err);
        });
    });
</script>

clipboard.js также есть на GitHub.

Изменение от 15 января 2016 года. Верхний ответ был отредактирован сегодня для ссылки на тот же API в моем ответе, опубликованном в августе 2015 года. Предыдущий текст инструктировал пользователей использовать ZeroClipboard. Просто хочу прояснить, что я не выдернул это из ответа jfriend00, а наоборот.

С разрывами строк (продолжение ответа от Альваро Монторо)

var ClipboardHelper = {

    copyElement: function ($element)
    {
       this.copyText($element.text())
    },
    copyText:function(text) // Linebreaks with \n
    {
        var $tempInput =  $("<textarea>");
        $("body").append($tempInput);
        $tempInput.val(text).select();
        document.execCommand("copy");
        $tempInput.remove();
    }
};

ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());

Еще лучший подход без flash или каких-либо других требований - это https://clipboardjs.com/. Все, что вам нужно сделать, это добавить data-clipboard-target="#toCopyElement" на любую кнопку, инициализировать его new Clipboard('.btn'); и он будет копировать содержимое DOM с идентификатором toCopyElement в буфер обмена. Это фрагмент, который копирует текст, указанный в вашем вопросе, по ссылке.

Одно ограничение заключается в том, что он не работает в сафари, но работает во всех других браузерах, включая мобильные, так как не использует флэш-память.

$(function(){
  new Clipboard('.copy-text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>

<p id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>

<a class="copy-text" data-clipboard-target="#content" href="#">copy Text</a>

<div class="form-group">
    <label class="font-normal MyText">MyText to copy</label>&nbsp;
    <button type="button" class="btn btn-default btn-xs btnCopy" data="MyText">Copy</button>
</div>


$(".btnCopy").click(function () {
        var element = $(this).attr("data");
        copyToClipboard($('.' + element));
  });

function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(element).text()).select();
    document.execCommand("copy");
    $temp.remove();
}

Вы можете использовать этот код для копирования входного значения на странице в буфере обмена, нажав кнопку

Это HTML

<input type="text" value="xxx" id="link" class="span12" />
<button type="button" class="btn btn-info btn-sm" onclick="copyToClipboard('#link')">
    Copy Input Value
</button>

Тогда для этого HTML, мы должны использовать этот код JQuery

function copyToClipboard(element) {
    $(element).select();
    document.execCommand("copy");
}

Это самое простое решение для этого вопроса

JQuery простое решение.

Должен быть активирован по клику пользователя.

$("<textarea/>").appendTo("body").val(text).select().each(function () {
            document.execCommand('copy');
        }).remove();
      <p style="color:wheat;font-size:55px;text-align:center;">How to copy a TEXT to Clipboard on a Button-Click</p>
    
    <center>
    <p id="p1">Hello, I'm TEXT 1</p>
    <p id="p2">Hi, I'm the 2nd TEXT</p><br/>
    
    <button onclick="copyToClipboard('#p1')">Copy TEXT 1</button>
    <button onclick="copyToClipboard('#p2')">Copy TEXT 2</button>
      
    </center>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
<script>
    function copyToClipboard(element) {
      var $temp = $("<input>");
      $("body").append($temp);
      $temp.val($(element).text()).select();
      document.execCommand("copy");
      $temp.remove();
    }
</script>

Очень важно, чтобы поле ввода не имело display: none, Браузер не будет выделять текст и, следовательно, не будет скопирован. использование opacity: 0 с шириной 0px, чтобы решить проблему.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <link href="css/index.css" rel="stylesheet" />
    <script src="js/jquery-2.1.4.min.js"></script>
    <script>
        function copy()
        {
            try
            {
                $('#txt').select();
                document.execCommand('copy');
            }
            catch(e)
            {
                alert(e);
            }
        }
    </script>
</head>
<body>
    <h4 align="center">Copy your code</h4>
    <textarea id="txt" style="width:100%;height:300px;"></textarea>
    <br /><br /><br />
    <div align="center"><span class="btn-md" onclick="copy();">copy</span></div>
</body>
</html>

Это самый простой способ скопировать контент

 <div id="content"> Lorepm ispum </div>
 <button class="copy" title="content">Copy Sorce</button>

function SelectContent(element) {
                        var doc = document
                            , text = doc.getElementById(element)
                            , range, selection
                        ;    
                        if (doc.body.createTextRange) {
                            range = document.body.createTextRange();
                            range.moveToElementText(text);
                            range.select();
                        } else if (window.getSelection) {
                            selection = window.getSelection();        
                            range = document.createRange();
                            range.selectNodeContents(text);
                            selection.removeAllRanges();
                            selection.addRange(range);

                        }
                         document.execCommand('Copy');
                    }
                    $(".copy").click(function(){

                         SelectContent( $(this).attr('title'));
                    });

Большинство из предложенных ответов создают дополнительные временные скрытые элементы ввода. Поскольку большинство браузеров в настоящее время поддерживают редактирование содержимого div, я предлагаю решение, которое не создает скрытые элементы, сохраняет форматирование текста и использует чистый JavaScript или библиотеку jQuery.

Вот минималистичная реализация скелета, использующая наименьшее количество строк кода, о которых я мог подумать:

//Pure javascript implementation:
document.getElementById("copyUsingPureJS").addEventListener("click", function() {
  copyUsingPureJS(document.getElementById("copyTarget"));
  alert("Text Copied to Clipboard Using Pure Javascript");
});

function copyUsingPureJS(element_id) {
  element_id.setAttribute("contentEditable", true);
  element_id.setAttribute("onfocus", "document.execCommand('selectAll',false,null)");
  element_id.focus();
  document.execCommand("copy");
  element_id.removeAttribute("contentEditable");
  
}

//Jquery:
$(document).ready(function() {
  $("#copyUsingJquery").click(function() {
    copyUsingJquery("#copyTarget");
  });
 

  function copyUsingJquery(element_id) {
    $(element_id).attr("contenteditable", true)
      .select()
      .on("focus", function() {
        document.execCommand('selectAll', false, null)
      })
      .focus()
    document.execCommand("Copy");
    $(element_id).removeAttr("contenteditable");
     alert("Text Copied to Clipboard Using jQuery");
  }
});
#copyTarget {
  width: 400px;
  height: 400px;
  border: 1px groove gray;
  color: navy;
  text-align: center;
  box-shadow: 0 4px 8px 0 gray;
}

#copyTarget h1 {
  color: blue;
}

#copyTarget h2 {
  color: red;
}

#copyTarget h3 {
  color: green;
}

#copyTarget h4 {
  color: cyan;
}

#copyTarget h5 {
  color: brown;
}

#copyTarget h6 {
  color: teal;
}

#pasteTarget {
  width: 400px;
  height: 400px;
  border: 1px inset skyblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="copyTarget">
  <h1>Heading 1</h1>
  <h2>Heading 2</h2>
  <h3>Heading 3</h3>
  <h4>Heading 4</h4>
  <h5>Heading 5</h5>
  <h6>Heading 6</h6>
  <strong>Preserve <em>formatting</em></strong>
  <br/>
</div>

<button id="copyUsingPureJS">Copy Using Pure JavaScript</button>
<button id="copyUsingJquery">Copy Using jQuery</button>
<br><br> Paste Here to See Result
<div id="pasteTarget" contenteditable="true"></div>

Вы можете просто использовать эту библиотеку для легкой реализации цели копирования!

https://clipboardjs.com/

Копирование текста в буфер обмена не должно быть сложным. Не требуется десятки шагов для настройки или сотни КБ для загрузки. Но, прежде всего, это не должно зависеть от Flash или какого-либо раздутого фреймворка.

Вот почему clipboard.js существует.

или же

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

Библиотека ZeroClipboard обеспечивает простой способ копирования текста в буфер обмена с помощью невидимого фильма Adobe Flash и интерфейса JavaScript.

Библиотека Clipboard-polyfill является полифилом для современного API-интерфейса для асинхронного буфера обмена на основе Promise.

установить в CLI:

npm install clipboard-polyfill 

импортировать как буфер обмена в файл JS

window.clipboard = require('clipboard-polyfill');

пример

Я использую его в комплекте с require("babel-polyfill"); и проверил его на хроме 67. Все хорошо для производства.

Вы можете скопировать отдельный текст отдельно от текста HTML-элемента.

        var copyToClipboard = function (text) {
            var $txt = $('<textarea />');

            $txt.val(text)
                .css({ width: "1px", height: "1px" })
                .appendTo('body');

            $txt.select();

            if (document.execCommand('copy')) {
                $txt.remove();
            }
        };

Текст для копирования находится в текстовом вводе, например: <input type="text" id="copyText" name="copyText"> и, при нажатии кнопки выше текст должен быть скопирован в буфер обмена, поэтому кнопка выглядит так:<button type="submit" id="copy_button" data-clipboard-target='copyText'>Copy</button> Ваш скрипт должен выглядеть так:

<script language="JavaScript">
$(document).ready(function() {
var clip = new ZeroClipboard($("#copy_button"), {
  moviePath: "ZeroClipboard.swf"
}); 
});

</script>

Для файлов CDN

примечание: ZeroClipboard.swf а также ZeroClipboard.js"файл должен находиться в той же папке, что и ваш файл, использующий эту функцию, ИЛИ вы должны включить, как мы включаем <script src=""></script> на наших страницах.

Почему бы вам просто не использовать этот код, я не понимаю?

      navigator.clipboard.writeText('text here...');

HTML-код здесь

    <input id="result" style="width:300px"/>some example text
    <button onclick="copyToClipboard('result')">Copy P1</button>
    <input type="text" style="width:400px" placeholder="Paste here for test" />

JS CODE:

     function copyToClipboard(elementId) {

                      // Create a "hidden" input
                      var aux = document.createElement("input");

                      aux.setAttribute("value", document.getElementById(elementId).value);
                      // Append it to the body
                      document.body.appendChild(aux);
                      // Highlight its content
                      aux.select();
                      // Copy the highlighted text
                      document.execCommand("copy");
                      // Remove it from the body
                      document.body.removeChild(aux);
                    }

Оба будут работать как шарм:),

JAVASCRIPT:

function CopyToClipboard(containerid) {
if (document.selection) { 
    var range = document.body.createTextRange();
    range.moveToElementText(document.getElementById(containerid));
    range.select().createTextRange();
    document.execCommand("copy"); 

} else if (window.getSelection) {
    var range = document.createRange();
     range.selectNode(document.getElementById(containerid));
     window.getSelection().addRange(range);
     document.execCommand("copy");
     alert("text copied") 
}}

Также в HTML,

<button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>

<div id="div1" >Text To Copy </div>

<textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>

JQUERY: https://paulund.co.uk/jquery-copy-clipboard

Очень простой. Вы, должно быть, ищете js navigator.clipboard.writeText("thistext");
Это просто скопирует текст «thistext». Теперь, чтобы заставить его работать при щелчке, используйте функцию jquery onclick и сохраните значение (текст, который вы хотите скопировать) в строке (если вам нужно, вы также можете использовать DOM, чтобы получить значение со страницы) и используйте эту строку копии и вместо «thistext» передайте переменную!

      function copyToClipboard(element) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($('span[id='+element+']').text()).select();
    document.execCommand("copy");
    $temp.remove();
}

Чистый JS, без встроенного onclick, для парных классов "контент - кнопка копирования". Было бы удобнее, если бы элементов было много)

(function(){

/* Creating textarea only once, but not each time */
let area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";

let content = document.querySelectorAll('.js-content');
let copy    = document.querySelectorAll('.js-copy');

for( let i = 0; i < copy.length; i++ ){
  copy[i].addEventListener('click', function(){
    area.style.display = "block";
    /* because the classes are paired, we can use the [i] index from the clicked button,
    to get the required text block */
    area.value = content[i].innerText;
    area.select();
    document.execCommand('copy');   
    area.style.display = "none";

    /* decorative part */
    this.innerHTML = 'Cop<span style="color: red;">ied</span>';
    /* arrow function doesn't modify 'this', here it's still the clicked button */
    setTimeout( () => this.innerHTML = "Copy", 2000 );
  });
}

})();
hr { margin: 15px 0; border: none; }
<span class="js-content">1111</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">2222</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">3333</span>
<button class="js-copy">Copy</button>

Поддержка старых версий браузера:

(function(){

var area = document.createElement('textarea');
document.body.appendChild( area );
area.style.display = "none";

var content = document.querySelectorAll('.js-content');
var copy    = document.querySelectorAll('.js-copy');

for( var i = 0; i < copy.length; i++ ){
  copyOnClick(i);
}

function copyOnClick(i){
  copy[i].addEventListener('click', function(){
    area.style.display = "block";
    area.value = content[i].innerText;
    area.select();
    document.execCommand('copy');   
    area.style.display = "none";
    
    var t = this;
    t.innerHTML = 'Cop<span style="color: red;">ied</span>';
    setTimeout( function(){
      t.innerHTML = "Copy"
    }, 2000 );
  });
}

})();
hr { margin: 15px 0; border: none; }
<span class="js-content">1111</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">2222</span>
<button class="js-copy">Copy</button>
<hr>
<span class="js-content">3333</span>
<button class="js-copy">Copy</button>

HTML:

      // you need bootstrap(js && css) and JQuery(js)
<span class="text-copy" value="your-text">text</span>

CSS:

      .text-copy {
  cursor: pointer;
  color: #0d6efd;
  text-decoration: underline;
}
.text-copy:hover {
  color: #1b6be4;
}

JS (используя JQuery):

      $(document).ready(function() {
  var elements = $('.copy-text');
  for(let i = 0; i < elements.length; i++) {
    const element = $(elements[i]);
    element.attr('data-toggle', 'tooltip')
           .attr('data-placement', 'top')
           .attr('title', `Tab to copy "${element.attr('value')}"`);
  }
  $('[data-toggle="tooltip"]').tooltip();
  $('.text-copy').click(function() {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($(this).attr('value')).select();
    document.execCommand("copy");
    $temp.remove();
  });
});

Вот элегантное решение Javascript

      <input type="text" value="Foo Bar" id="your_input">
<button onclick="copy()">Copy text</button>

<script type="application/javascript">
function copy() {
  var copiedtext = document.getElementById("your_input");
  copiedtext.select();
  copiedtext.setSelectionRange(0, 99999); //for mobile devices
  navigator.clipboard.writeText(copiedtext.value);
  alert("You just copied " + copiedtext.value);
}
</script>

используйте эту функцию:

      function copy_input($input) {
        $input.focus();
        $input.select();
        try {  
            var successful = document.execCommand('copy');  
        } catch(err) {  
            console.error('Unable to copy'); 
        }       
    }   

вызов:

      $(".copy-text").on("click",() => {
    copy_input("#input_Id")
})

Я делал это прямо сейчас и просто хотел знать, есть ли способ лучше, чем мой, но нет.

Вы можете использовать мой код, он копирует текст и показывает всплывающую подсказку.

Голова

      <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<link href="https://cdn.jsdelivr.net/npm/remixicon@2.2.0/fonts/remixicon.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

Тело

      <div class="alert alert-primary alert-dismissible mb-0 py-1" role="alert" id="liveAlert">
    <div class="container d-flex justify-content-between">
      <button type="button" class=" btn align-self-center ms-4 copytext" data-bs-toggle="tooltip" data-bs-placement="top" title=""><strong>Good news!</strong>  You just got 10% off, use your coupon <span class="fw-bold bg-secondary text-white px-2 maintext">store10off</span>. <i class="ri-file-copy-line"></i></button>
      <button type="button" class="btn align-self-center" data-bs-dismiss="alert" aria-label="Close"><strong class="fw-bold fs-4"><i class="ri-close-fill"></i></strong></button>
    </div>
    </div>

Функция

      <script>
    $('.copytext').click(function(){
        var thistooltip = $(this);
        var thistext = $(this).children('.maintext').text();
        navigator.clipboard.writeText(thistext);
        $(this).attr('title','copied');
        setTimeout(function(){$(thistooltip).tooltip("toggle");}, 800);
    });
</script>
       document.getElementById('markup-copy').addEventListener('click', function() {
               var txt = "Your text Here";
                    $("<textarea/>").appendTo("body").val(txt).select().each(function () {
                    document.execCommand('copy');
                }).remove();
            });
Другие вопросы по тегам