# 其他页面功能

一些其他功能

# 复制粘贴功能

旧时代的代码

// 创建一个临时的 textarea 元素
const textarea = document.createElement('textarea')
// 设置 textarea 的内容
textarea.value = inputElement.value
// 防止在页面上显示 textarea
textarea.setAttribute('readonly', '')
textarea.style.position = 'absolute'
textarea.style.left = '-9999px'
// 将 textarea 添加到页面中
document.body.appendChild(textarea)
// 选中 textarea 的内容
textarea.select()
// 尝试执行复制操作
const success = document.execCommand('copy')
// 移除 textarea 元素
document.body.removeChild(textarea)
// 根据复制操作的成功与否给出提示
if (success) {
  alert('复制成功!')
} else {
  alert('复制失败,请手动复制。')
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

新时代的代码

# 复制功能的实现

const copyText = async text => {
  try {
    await navigator.clipboard.writeText(text)
    console.log('复制成功!')
  } catch (err) {
    console.error('无法复制: ', err)
  }
}
1
2
3
4
5
6
7
8

# 粘贴功能的实现

const pasteText = async () => {
  try {
    const text = await navigator.clipboard.readText()
    console.log('粘贴成功: ', text)
  } catch (err) {
    console.error('无法粘贴: ', err)
  }
}
1
2
3
4
5
6
7
8

为了兼容,我们可以在代码里加一个 Permissions API 的判断, 例如

if (navigator.clipboard && navigator.permissions) {
  await navigator.clipboard.writeText(val)
}
1
2
3

# 完整兼容代码

const copyText = async val => {
  try {
    // 使用现代 API 尝试复制
    if (navigator.clipboard && navigator.permissions) {
      await navigator.clipboard.writeText(val)
      return // 如果成功,直接返回
    }

    // 降级方案
    const textArea = document.createElement('textArea')
    textArea.value = val
    textArea.style.width = 0
    textArea.style.position = 'fixed'
    textArea.style.left = '-999px'
    textArea.style.top = '10px'
    textArea.setAttribute('readonly', 'readonly')
    document.body.appendChild(textArea)
    textArea.select()

    // 尝试执行复制操作
    const success = document.execCommand('copy')
    if (!success) {
      throw new Error('无法复制文本')
    }

    // 清理
    document.body.removeChild(textArea)
  } catch (err) {
    console.error('复制失败:', err)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
知识汇总   |