本文介绍了如何将文本从div复制到剪贴板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是用户点击此按钮时的代码:

Here is my code for when the user clicks on this button:

<button id="button1">Click to copy</button>

如何复制此div中的文本?

How do I copy the text inside this div?

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


推荐答案

两者都会像魅力一样:),

Both will works like a charm :),


  1. JAVASCRIPT:

  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>

这篇关于如何将文本从div复制到剪贴板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 06:32
查看更多