html
< style>
. copy_box {
position : relative;
width : 400px;
height : 40px;
}
. copy_input {
width : 100 % ;
height : 100 % ;
font- size: 14px;
padding- left: 13px;
padding- right: 80px;
border : 1px solid #e1e7f2;
border- radius: 4px;
color : #333 ;
}
. copy_button{
padding : 0 20px;
height : 100 % ;
background : #fff;
position : absolute;
right : 0 ;
top : 0 ;
border : 1px solid #e1e7f2;
border- radius: 4px;
border- top- left- radius: 0 ;
border- bottom- left- radius: 0 ;
cursor : pointer;
font- size: 14px;
}
. hide {
position : absolute;
top : 0 ;
left : 0 ;
opacity : 0 ;
z- index: - 10 ;
}
< / style>
< div class = "copy_box" >
< input class = "copy_input" type= "text" value= "123" disabled>
< button class = "copy_button" > 复制< / button>
< input class = "hide" type= "text" >
< / div>
js
$ ( function ( ) {
$ ( ".copy_button" ) . click ( function ( ) {
var text = $ ( this ) . prev ( ) . val ( ) ;
$ ( this ) . next ( ) . val ( text) ;
$ ( this ) . next ( ) . select ( ) ;
document. execCommand ( "copy" ) ;
alert ( "复制成功" ) ;
} ) ;
} ) ;
注意:
如果是输入框,可以通过 select() 方法,选中输入框的文本,然后调用 copy 命令,将文本复制到剪切板
但是 select() 方法只对 input 和 textarea 有效,对disabled属性的的input没有效果,可以在在页面中添加一个表单,把它隐藏掉,不能display:none,不然也拿不到复制的内容
非表单的复制功能
$( ".copy_btn") .click( function ( ) {
$( ".pop-success") .show( )
setTimeout( function ( ) {
$( ".pop-success") .hide( )
} , 2000 )
const textElement = $( this) .next( ) [ 0 ] ;
copyText( textElement) ;
} ) ;
function copyText( element) {
const range = document.createRange( ) ;
range.selectNode( element) ;
const selection = window.getSelection( ) ;
selection.removeAllRanges( ) ;
selection.addRange( range) ;
try {
const successful = document.execCommand( 'copy' ) ;
const msg = successful ? 'successful' : 'unsuccessful' ;
console.log( 'Copy text command was ' + msg) ;
} catch ( err) {
console.error( 'Unable to copy text' , err) ;
}
// Deselect the text
selection.removeAllRanges( ) ;
} ```