JavaScript realizes one-click copy (id, account number)


There are many times in the front end that one-click copying of account numbers and passwords is required. For example, QQ copying of QQ accounts, and personal information pages of some program applications will have a one-click copying function. Let me share with you the implementation method of one-click copying

HTML preparation

Prepare HTML in advance so that everyone can understand it more clearly

<!-- 文本复制 -->
<div class="text" >
	日落西山你不在,东山再起你是谁?
	<input type="text" id="inp" />
</div>
<button type="button" id="but" onclick="but()">复制</button>

The reason why the structure is written in this way is that the JavaScript one-click copy function needs to use the document.execCommand() method. This method cannot copy the content in the div, but can only copy the value in the input. Effect
:
html structure style

JavaScript logic

The main idea is to get the text in the div element first, then change the value of the input box to the text in the div element, select the value of the input box, and then call the document.execCommand() event, which needs to pass a 'copy 'String, which means to copy the selected content

// 文本复制
function but(){
    
    
	let text = document.getElementsByClassName('text')[0].innerText;// 获取到div元素中的文本
	let inp = document.getElementById('inp');// 获取到input框
	inp.value = text;// 将input框的值赋值为div元素中的文本
	inp.select(); // 选中input框中的文本
	document.execCommand("copy");// 调用document的execCommand事件
}

Now just run the HTML, and click the copy button to copy the text in the div element to the clipboard.
Normally, the input box will not be displayed. You can add styles to it to hide it.

css

#inp{
    
    
	position: absolute;
	left: 0;
	opacity: 0;
}

Effect:
HTML hides the input effect

The whole is actually relatively easy to understand, just remember to use the document.exec Command() method, and you also need to know that you can’t copy ordinary text, only the value of input

Guess you like

Origin blog.csdn.net/qq_68862343/article/details/131531049