作者:睡姿决定发型 | 来源:互联网 | 2023-09-25 17:00
PC端
import { message } from 'ant-design-vue' ; export const clipBoard = ( value: string ) => { const textarea: HTMLTextAreaElement = document. createElement ( 'textarea' ) ; textarea. setAttribute ( 'readonly' , 'readonly' ) ; textarea. value = value; document. body. appendChild ( textarea) ; textarea. setSelectionRange ( 0 , textarea. value. length) ; textarea. select ( ) ; document. execCommand ( 'copy' ) ; if ( document. body. removeChild ( textarea) ) { message. success ( '复制成功' ) ; } else { message. error ( '复制失败' ) ; } } ;
移动端
export function copyText ( text: string ) { let input = document. querySelector< HTMLInputElement> ( '#copy-input' ) ; if ( ! input) { input = document. createElement ( 'input' ) ; input. id = "copy-input" ; input. readOnly = true ; input. style. position = "fixed" ; input. style. left = "-1000px" ; input. style. zIndex = "-1000" ; document. body. appendChild ( input) ; } input. value = text; selectText ( input, 0 , text. length) ; if ( document. execCommand ( 'copy' ) ) { document. execCommand ( 'copy' ) ; Toast ( '已复制到粘贴板' ) ; } else { console. log ( '不兼容' ) ; } input. blur ( ) ; } export function selectText ( textbox: any, startIndex: any, stopIndex: any ) { if ( textbox. createTextRange) { const range = textbox. createTextRange ( ) ; range. collapse ( true ) ; range. moveStart ( 'character' , startIndex) ; range. moveEnd ( 'character' , stopIndex - startIndex) ; range. select ( ) ; } else { textbox. setSelectionRange ( startIndex, stopIndex) ; textbox. focus ( ) ; } }