简体   繁体   中英

How to clipboard some text from a div

How to copy text from div element on mobile devices.

Here is a example:

<div class="banks" onclick="copyAccountNumber(this);">
    <div>
        <img src="../../../../images/bank/khaan_bank_32x32.png" alt="">
        <!-- <input onclick="setTimeout(function() {this.setSelectionRange(0, 9999);}, 1);" value="5037 6391 20" readonly="true"> -->
        <div class="js_account">5037 6391 20</div>
        <span>Хаан банк</span>
    </div>
    <div>
        <img src="../../../../images/bank/khas_bank_32x32.png" alt="">
        <!-- <input onclick="this.setSelectionRange(0, 9999);" value="5002 0860 50" readonly="true"> -->
        <div class="js_account">5002 0860 50</div>
        <span>Хас банк</span>
    </div>
</div>

And javascript:

window.copyAccountNumber = function(elem) {
    let divs = elem.querySelectorAll(".js_account");
    for (var i = 0; i < divs.length; i++) {
        divs[i].addEventListener("click", function(e) {
            copyToClipboard(this);
        });
    }
};

function copyToClipboard(el) {
    var oldContentEditable = el.contentEditable,
        oldReadOnly = el.readOnly,
        range = document.createRange();

    el.contentEditable = true;
    el.readOnly = false;
    range.selectNodeContents(el);

    var s = window.getSelection();
    s.removeAllRanges();
    s.addRange(range);

    el.setSelectionRange(0, 9999);

    el.contentEditable = oldContentEditable;
    el.readOnly = oldReadOnly;

    document.execCommand('copy');
}

But above not working anyways. I need to clipboard texts from .js_account but its not working well. What did i do wrong ? Any advice ?

You can take my code for example and change as per you requirement.. I have validated this code.. It is working fine.. Hope it's helpful for you..

Copying:------

<button onclick="myFunction()">
    <div id="js_account">5037 6391 20</div>
</button>

<p>The document.execCommand() method is not supported in IE8 and earlier.</p>

<script>
function myFunction() {
  const el = document.createElement('input');
  var copyText = document.getElementById("js_account");
  el.value = copyText.innerText;
  document.body.appendChild(el);
  el.select();
  document.execCommand("copy");
  document.body.removeChild(el);
  alert("Copied the text: " + copyText.innerText);
}
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM