Words etch cherished moments.
OG

给你的网站添加可爱的小尾巴

1,165 words, 3 min read
2018/07/27 AM
676 views

有些时候我们开发碰到问题,在CSDN上复制别人的代码时会发现附带了这种可爱的小尾巴

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
const promise = new Promise((resolve, reject) => { // ... }) 作者:Superficial 链接:https://localhost:8888/article/1 来源:Superficial Blog

#先想想伪代码如何实现

  1. 监听浏览器的copy事件
  2. 获取选中的字符串信息 window.getSelection
  3. 通过事件对象中的对象把数据设置到剪切板中 event.clipboardData

#功能实现

          
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
export const copyright = () => { const copyText = () => { return [ '', '作者:Superficial', `链接:${location.href}`, '来源:Superficial Blog' ].join('\n') } const buildText = content => content + copyText() document.addEventListener('cpoy', event => { if (window.getSelection) return // 防止浏览器没有该方法 const content = window.getSelection()?.toString() // 这里使用了es6的可选链式操作符 event.clipboardData?.setData('text/plain', buildText(content)) }) }

#参考资料

阮一峰博客-剪贴板操作 Clipboard API 教程

Creative Commons BY-NC 4.0
https://zhangwurui.cn/article/17
0/0comments
Guest
Start the discussion...
Be the first to comment