Home > Web Front-end > JS Tutorial > body text

Detailed answer to JS operation clipboard

亚连
Release: 2018-06-06 10:13:51
Original
1927 people have browsed it

This article introduces how to use JS to operate the clipboard function, and shares the example code. Friends who need it can learn it.

Javascript can easily manipulate client clipboard content, but it is only applicable to IE5 and above browsers.

Javascript can use the window.clipboardData object to handle clipboard content.

Method setData(param1, param2) to save to the clipboard.

param1: Data type text or URL, etc.

param2: Data content.

The method of reading data from the clipboard getdata(param1)

The method of clearing data clearData(param1)

<HTML>  
<HEAD>  
<TITLE>测试操作剪贴板</TITLE>  
</HEAD>  
<script>  
function copyToClipboard()  
{  
 var d=document.all("source").value;  
 window.clipboardData.setData(&#39;text&#39;,d);  
}  
</script>  
<BODY>  
<button onclick="copyToClipboard();">拷贝</button>  
<input type="text" size=20 id="source" value="测试数据">  
<br>  
<button onclick="alert(window.clipboardData.getData(&#39;text&#39;));">显示</button>  
<button onclick="window.clipboardData.clearData(&#39;text&#39;);">清空</button>  
</BODY>  
</HTML>  

下面是另一个例子实现页面中选中字符,并拖拉到文本区功能。注意其中的window.event.dataTransfer对象也可处理剪贴板内容,不过只能用在 drag-and-drop 操作中。
<HTML>  
<HEAD>  
<TITLE>测试操作剪贴板2</TITLE>  
</HEAD>  
<script>  
function transferDrop() {  
   window.event.srcElement.innerText = window.event.dataTransfer.getData("text");  
   window.event.returnValue = false;  
}  
function transferDrag() {  
 window.event.dataTransfer.dropEffect = &#39;move&#39;;  
 window.event.returnValue = false;  
}  
</script>  

<BODY>
<p id="mySource" ondragstart="window.event.dataTransfer.effectAllowed = &#39;move&#39;;">选择我们并把我们拖到下面的textarea</p>  
<textarea id="myTarget" ondrop="transferDrop();" ondragover="window.event.returnValue = false;" ondragenter="transferDrag();">  
</textarea>
</BODY>  
</HTML>
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Using gm to crop composite images under Nodejs

How to use babel installation and configuration tutorial

How to configure babel configuration file in vue-cli

The above is the detailed content of Detailed answer to JS operation clipboard. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template