react & vue & angular

Vue自定义指令--实现跟随鼠标浮层

2022-03-02  本文已影响0人  NemoExpress

项目中有一个需求,需要鼠标划入后显示相关信息,信息要跟随鼠标指针显示

思路

代码

采用局部指令的方式进行

......
 methods: {
   ....
  },
  directives: {
    // 自定义提示指令
    tooltip: {
      componentUpdated: function(el, binding) {
          // 鼠标移入时,将浮沉元素插入到body中
        el.onmouseenter = function(e) {
          // 创建浮层元素并设置样式
          const vcTooltipDom = document.createElement('div')
          vcTooltipDom.style.cssText = `
          overflow: auto;
          position:absolute;
          background: #fff;;
          color:#666;
          box-shadow: rgba(168, 168, 168, 0.295) 1px 2px 10px;
          border-radius:5px;
          padding:10px;
          display:inline-block;
          font-size:14px;
          z-index:2
        `
          // 设置id方便寻找
          vcTooltipDom.setAttribute('id', 'vc-tooltip')
          // 将浮层插入到body中
          document.body.appendChild(vcTooltipDom)
          // 浮层中的文字 通过属性值传递动态的显示文案
          document.getElementById('vc-tooltip').innerHTML = el.getAttribute('tips')
        }
        // 鼠标移动时,动态修改浮沉的位置属性
        el.onmousemove = function(e) {
          const vcTooltipDom = document.getElementById('vc-tooltip')
          vcTooltipDom.style.top = e.clientY + 15 + 'px'
          vcTooltipDom.style.left = e.clientX + 15 + 'px'
        }
        // 鼠标移出时将浮层元素销毁
        el.onmouseleave = function() {
          // 找到浮层元素并移出
          const vcTooltipDom = document.getElementById('vc-tooltip')
          vcTooltipDom && document.body.removeChild(vcTooltipDom)
        }
      }
    }
  }
......

使用

 <div  :tips="共有6个任务执行成功"   v-tooltip>

效果

tips
上一篇下一篇

猜你喜欢

热点阅读