CMVR-IOT-UI/src/directive/common/copyText.js

66 lines
1.6 KiB
JavaScript
Raw Normal View History

2025-08-21 14:11:58 +08:00
/**
* v-copyText 复制文本内容
* Copyright (c) 2022 ruoyi
*/
export default {
beforeMount(el, { value, arg }) {
if (arg === "callback") {
2026-07-28 16:26:07 +08:00
el.$copyCallback = value
2025-08-21 14:11:58 +08:00
} else {
2026-07-28 16:26:07 +08:00
el.$copyValue = value
2025-08-21 14:11:58 +08:00
const handler = () => {
2026-07-28 16:26:07 +08:00
copyTextToClipboard(el.$copyValue)
2025-08-21 14:11:58 +08:00
if (el.$copyCallback) {
2026-07-28 16:26:07 +08:00
el.$copyCallback(el.$copyValue)
2025-08-21 14:11:58 +08:00
}
2026-07-28 16:26:07 +08:00
}
el.addEventListener("click", handler)
el.$destroyCopy = () => el.removeEventListener("click", handler)
2025-08-21 14:11:58 +08:00
}
}
}
function copyTextToClipboard(input, { target = document.body } = {}) {
2026-07-28 16:26:07 +08:00
const element = document.createElement('textarea')
const previouslyFocusedElement = document.activeElement
2025-08-21 14:11:58 +08:00
2026-07-28 16:26:07 +08:00
element.value = input
2025-08-21 14:11:58 +08:00
// Prevent keyboard from showing on mobile
2026-07-28 16:26:07 +08:00
element.setAttribute('readonly', '')
2025-08-21 14:11:58 +08:00
2026-07-28 16:26:07 +08:00
element.style.contain = 'strict'
element.style.position = 'absolute'
element.style.left = '-9999px'
element.style.fontSize = '12pt' // Prevent zooming on iOS
2025-08-21 14:11:58 +08:00
2026-07-28 16:26:07 +08:00
const selection = document.getSelection()
const originalRange = selection.rangeCount > 0 && selection.getRangeAt(0)
2025-08-21 14:11:58 +08:00
2026-07-28 16:26:07 +08:00
target.append(element)
element.select()
2025-08-21 14:11:58 +08:00
// Explicit selection workaround for iOS
2026-07-28 16:26:07 +08:00
element.selectionStart = 0
element.selectionEnd = input.length
2025-08-21 14:11:58 +08:00
2026-07-28 16:26:07 +08:00
let isSuccess = false
2025-08-21 14:11:58 +08:00
try {
2026-07-28 16:26:07 +08:00
isSuccess = document.execCommand('copy')
2025-08-21 14:11:58 +08:00
} catch { }
2026-07-28 16:26:07 +08:00
element.remove()
2025-08-21 14:11:58 +08:00
if (originalRange) {
2026-07-28 16:26:07 +08:00
selection.removeAllRanges()
selection.addRange(originalRange)
2025-08-21 14:11:58 +08:00
}
// Get the focus back on the previously focused element, if any
if (previouslyFocusedElement) {
2026-07-28 16:26:07 +08:00
previouslyFocusedElement.focus()
2025-08-21 14:11:58 +08:00
}
2026-07-28 16:26:07 +08:00
return isSuccess
2025-08-21 14:11:58 +08:00
}