2021-06-29

元素鼠标缩放自定义指令

import Vue from 'vue'
// import _ from 'lodash'
// 缩放容器设置
let containerScale = {
  init: 1, // 初始倍率
  min: 0.2, // 最小倍率
  max: 3, // 最大倍率
  onceNarrow: 0.05, // 每次缩放比率
  onceEnlarge: 0.05 // 每次缩放比率
}

// 缩放样式配置
let container = {
  scale: 1, // 缩放倍率
  scaleOrigin: { // 缩放中心点
    x: 0,
    y: 0
  },
  scaleShow: '100%' // 缩放百分比
}

// 定义缩放指令
Vue.directive('scale', {
  bind (el) {
    const scaleDom = el
    const scaleFn = ev => {
      if (ev.deltaY < 0) {
        // 放大
        // 计算缩放倍率
        let newScale = handleAdd(container.scale, containerScale.onceEnlarge)
        if (newScale <= containerScale.max) {
          container.scale = newScale
          container.scaleShow = handleMul(container.scale, 100)
          // 渲染视图
          scaleDom.style.transform = `scale(${newScale})`
        }
      } else if (container.scale) {
        // 缩小
        // 计算缩放倍率
        let newScale = handleSub(container.scale, containerScale.onceNarrow)
        if (newScale >= containerScale.min) {
          container.scale = newScale
          container.scaleShow = handleMul(container.scale, 100)
          // 渲染视图
          scaleDom.style.transform = `scale(${newScale})`
        }
      }
    }
    // 监听鼠标滚轮事件
    scaleDom.onmousewheel = ev => {
      ev.preventDefault()
      // _.throttle(scaleFn(ev), 100)
      scaleFn(ev)
    }
  }
})

/**
 * @name:handleMul
 * @description:除法计算
 * @param {Number}:参数1 参数2
 */
function handleMul (a, b) {
  let c = 0
  let d = a.toString()
  let e = b.toString()
  try {
    c += d.split('.')[1].length
  } catch (f) { }
  try {
    c += e.split('.')[1].length
  } catch (f) { }
  return (Number(d.replace('.', '')) * Number(e.replace('.', ''))) / Math.pow(10, c)
}
/**
 * @name:handleAdd
 * @description:加法计算
 * @param {Number}:参数1 参数2
 */
function handleAdd (a, b) {
  let c, d, e
  try {
    c = a.toString().split('.')[1].length
  } catch (f) {
    c = 0
  }
  try {
    d = b.toString().split('.')[1].length
  } catch (f) {
    d = 0
  }
  // eslint-disable-next-line no-sequences
  return (e = Math.pow(10, Math.max(c, d))), (handleMul(a, e) + handleMul(b, e)) / e
}
/**
 * @name:handleSub
 * @description:减法计算
 * @param {Number}:参数1 参数2
 */
function handleSub (a, b) {
  let c, d, e
  try {
    c = a.toString().split('.')[1].length
  } catch (f) {
    c = 0
  }
  try {
    d = b.toString().split('.')[1].length
  } catch (f) {
    d = 0
  }
  // eslint-disable-next-line no-sequences
  return (e = Math.pow(10, Math.max(c, d))), (handleMul(a, e) - handleMul(b, e)) / e
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值