vue

自定义dom的title样式

2021-12-23  本文已影响0人  羊驼626

代码:

 // tooltip.js
export default class Tooltip {
  constructor () {
    this.dom = document.createElement('div')
    document.body.appendChild(this.dom)
    this.dom.style =
      `display: none;
      max-width: 484px;
      position: fixed;
      transform: translateY(-50%);
      background: rgba(17, 17, 17, 0.8);
      color: #fff;
      padding: 10px 14px;
      border-radius: 4px`
  }

  static getInstance (text) {
    if (!this.instance) {
      this.instance = new Tooltip()
    }
    this.instance.dom.innerText = text
    return this.instance
  }

  setPosition ({ x, y }) {
    this.show()
    this.dom.style.left = `${x}px`
    this.dom.style.top = `${y}px`
  }

  show () {
    this.dom.style.display = 'block'
  }

  hidden () {
    this.dom.style.display = 'none'
  }

  destory () {
    document.body.removeChild(this.dom)
    this.dom = null
  }
}

使用:

import Tooltip from '@/utils/tooltip.js'

mousemove (e) {
      Tooltip.getInstance(e.target.innerText).setPosition({
        x: e.clientX + 20,
        y: e.clientY + 10
      })
    },
    mouseleave () {
      Tooltip.getInstance().hidden()
    }
上一篇下一篇

猜你喜欢

热点阅读