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

Introduction to the implementation method of JavaScript operating clipboard

不言
Release: 2019-03-26 10:23:13
forward
3782 people have browsed it

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>
Copy after login

js method

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

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

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

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>
Copy after login

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')
Copy after login

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!

Related labels:
source:segmentfault.com
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