Home  >  Article  >  Web Front-end  >  Introduction to the implementation method of JavaScript operating clipboard

Introduction to the implementation method of JavaScript operating clipboard

不言
不言forward
2019-03-26 10:22:543668browse

This article brings you an introduction to the implementation method of JavaScript operating clipboard. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

You can operate the copy, cut and paste of the clipboard through js

Methods and elements used

DOM elements

<textarea> </textarea>
<input>

js method

// 选中输入框中的所有文本
inputElement.select()

// 选中输入框中的部分文本
inputElement.setSelectionRange(start, end)

// 对选中的文本进行 复制 / 剪切 / 粘贴 操作
document.execCommand('copy/cut/paste')

Implementation principle

is to operate the textarea input input box through js. You can only operate the input box and not other elements.
All copy/cut/paste operations must be performed after selecting the text in the input box.

Specific example

Write an example to show it

HTML

<label>测试内容:</label>
<textarea>ABCDEFGHIJKLMNOPQRSTUVWXYZ</textarea>
<textarea></textarea>

js and debug it directly in the console

Use shift enter Enter the command in the console on a new line

JS

// 选中文本
var text = document.querySelector('#text');
text.focus();
text.setSelectionRange(3,13);

// 操作文本
document.execCommand('cut')

After selection

Introduction to the implementation method of JavaScript operating clipboard

After performing the cut operation, manually paste it into This is the

Introduction to the implementation method of JavaScript operating clipboard

# in the input box below.

This article has ended here. For more other exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!

The above is the detailed content of Introduction to the implementation method of JavaScript operating clipboard. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete