当前位置: 首页 > news >正文

复制所绑定元素文本的vue自定义指令

最近写了一个复制所绑定元素文本的vue自定义指令,给大家分享一下。

import { ElMessage } from 'element-plus'

// data-* 属性名
const dataCopyBtnTextAttribute = 'data-copy-btn-text'
// 复制按钮的class,结合项目实际进行设置
const copyBtnClass = 'icon-copy'

// 复制文本的方法
const copyText = data => {
  const input = document.createElement('input')
  input.setAttribute('readonly', 'readonly')
  input.setAttribute('value', data)
  input.style.position = 'absolute'
  input.style.left = '-100px'
  input.style.top = '-100px'
  input.style.opacity = '0'
  document.body.appendChild(input)
  input.select()
  document.execCommand('copy')
  setTimeout(() => {
    document.body.removeChild(input)
  })
}

// 设置 data-* 属性
function setSign(el) {
  el.setAttribute(dataCopyBtnTextAttribute, el.innerText)
}

// 移除 data-* 属性
function removeSign(el) {
  el.removeAttribute(dataCopyBtnTextAttribute)
}

// 获取 data-* 属性
function getSign(el){
  return el.getAttribute(dataCopyBtnTextAttribute)
}

// 生成复制按钮
function getCopyBtn(el){
   const iDom = document.createElement('i')
   iDom.className = `iconfont ${copyBtnClass}`
   Object.assign(iDom.style,{
    color:'blue',
    cursor:'pointer',
    marginLeft:'4px'
   })
    // 添加点击事件 
   iDom.addEventListener('click',() => {
    copyText(el.innerText)
    ElMessage({
      message: '复制成功',
      type: 'success',
      duration:1000
    })
   }) 
   return iDom
}

// 添加复制按钮
function addCopyBtn(el){
  // 当节点内容发生变化时,移除复制按钮,当复制的文本有值时,重新添加复制按钮
  if(getSign(el) !== el.innerText){
    removeCopyBtn(el)
    if(!!el.innerText){
      el.appendChild(getCopyBtn(el))
      setSign(el)
    }
  }
}

// 移除复制按钮
function removeCopyBtn(el){
  removeSign(el)
  var copyBtns = el.querySelectorAll(`.${copyBtnClass}`);
  copyBtns.forEach((element) => {
    el.removeChild(element)
    element = null
  })
}

export default {
  mounted(el, binding) {
    addCopyBtn(el)
  },
  updated(el, binding) {
    addCopyBtn(el)
  },
  beforeUnmount(el, binding){
    removeCopyBtn(el)
  }
}

相关文章:

  • 【论文解析】Fast prediction mode selection and CU partition for HEVC intra coding
  • flink-cdc同步数据到doris中
  • 算法的复杂性分析以及时间复杂度的表示方法
  • JavaSE学习笔记25-反射(reflection)
  • 顺序表和STL——vector【 复习笔记】
  • C++ IDE设置 visual studio 2010安装、注册、使用
  • 一周学会Flask3 Python Web开发-flask3模块化blueprint配置
  • 【Go语言快速上手】第二部分:Go语言进阶之工具与框架
  • L2-【英音】地道语音语调
  • 自由学习记录(37)
  • python学智能算法(二)|模拟退火算法:进阶分析
  • PHP 会话(Session)实现用户登陆功能
  • Flutter CupertinoNavigationBar iOS 风格导航栏的组件
  • 10-R数组
  • LeetCode 热题 100_在排序数组中查找元素的第一个和最后一个位置(65_34_中等_C++)(二分查找)(一次二分查找+挨个搜索;两次二分查找)
  • 独立开发者如何寻找产品设计灵感
  • 大规模 RDMA AI 组网技术创新:算法和可编程硬件的深度融合
  • 基于Spring Boot的兴顺物流管理系统设计与实现(LW+源码+讲解)
  • eclips 快捷键
  • java方法学习
  • 西藏日喀则市拉孜县发生5.5级地震,震感明显部分人被晃醒
  • 中美经贸高层会谈在日内瓦结束,中国代表团将举行发布会
  • 上海消防全面推行“检查码”,会同相关部门推行“综合查一次”
  • 2025年上海市模范集体、劳动模范和先进工作者名单揭晓
  • 重温经典|《南郭先生》:不模仿别人,不重复自己
  • 近4小时会谈、3项联合声明、20多份双边合作文本,中俄元首今年首次面对面会晤成果颇丰