如何从div中剪贴板一些文本

时间:2018-12-10 07:11:29

标签: javascript android ios

如何在移动设备上从div元素复制文本。

这里是一个例子:

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

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

但是上面仍然无法正常工作。我需要剪切.js_account中的文本,但是效果不佳。我做错了什么 ?有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您可以以我的代码为例,并根据需要进行更改。.我已经验证了此代码..它可以正常工作..希望它对您有帮助。.

复制:------

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