首页 文章

如何从div剪贴一些文本

提问于
浏览
-1

如何从移动设备上的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 回答

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

相关问题