Подтвердить что ты не робот

Нажмите кнопку копирования в буфер обмена, используя jQuery

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

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

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

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

4b9b3361

Ответ 1

Изменить с 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">

Ответ 2

Существует и другой способ, отличный от 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" />

Ответ 3

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, а наоборот.

Ответ 4

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

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;" />

Ответ 5

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

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());

Ответ 6

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

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

$(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 standard dummy text ever since the 1500s</p>

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

Ответ 7

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

Это 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");
}

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

Ответ 8

<!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>

Ответ 9

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

 <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'));
                    });

Ответ 10

<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();
}

Ответ 11

Простое решение jQuery.

Должно быть вызвано щелчком пользователя.

$("<textarea/>").appendTo("body").val(text).select().each(function () {
            document.execCommand('copy');
        }).remove();

Ответ 12

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

Ответ 13

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

https://clipboardjs.com/

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

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

или

https://github.com/zeroclipboard/zeroclipboard

http://zeroclipboard.org/

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

Ответ 14

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

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

</script>

Для CDN файлов

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

Ответ 15

Большинство предложенных ответов создают дополнительный временный скрытый элемент ввода. Поскольку большинство браузеров в настоящее время поддерживают редактирование содержимого 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>

Ответ 16

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);
                    }

Ответ 17

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

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

npm install clipboard-polyfill 

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

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

пример

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

Ответ 18

Вы можете скопировать отдельный текст отдельно от текста 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();
            }
        };

Ответ 19

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

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

Ответ 20

Чистый 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 does not modify 'this', here it 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>

Ответ 21

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

  1. 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>
  1. Jquery:

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