原生js实现元素放大缩小

<template>
  <div id="app"
    @mousemove="handleMousemove"
    ref="resize"
    @mousedown="handleMousedown"
    @mouseup="handleMouseup"
    :style="{ cursor: cursorResize ? 'se-resize' : 'default' }">
    <div class="box"></div>
  </div>
</template>

<script>
export default {
  name: 'App',
  components: {
    // HelloWorld,
    // TestTest
    // ResizeComp
  },
  data(){
    return {
      startX: 0,
      startY: 0,
      down: false,
      resizeStatus: false,
      cursorResize: false
    }
  },
  methods: {
    // down置为true,记录鼠标点下的位置
    handleMousedown(e){
      this.down = true
      this.startX = e.pageX
      this.startY = e.pageY
    },

    // 鼠标抬起切换down状态
    handleMouseup(){
      this.down = false
      document.onmousemove = null
      document.onmousedown = null
      document.onmouseup = null
    },

    // 
    handleMousemove(e){
      // 获取鼠标的实时位置
      let curX = e.clientX
      let curY = e.clientY

      let target = this.$refs.resize.querySelector('.box')

      // 获取目标元素右下角的位置
      let x = target.getBoundingClientRect().right
      let y = target.getBoundingClientRect().bottom

      // 计算鼠标距离右下角的位置
      let increaseX = curX - x
      let increaseY = curY - y

      // 鼠标进入右下角区域,改变鼠标样式
      if(curX >= x - 5 && curX <= x + 5 && curY >= y - 5 && curY <= y + 5){
        this.cursorResize = true
      } else {
        this.cursorResize = false
      }

      // 按下开始拖拽改变目标元素大小
      if(this.down){
        this.resizeStatus = true
        target.style.width = target.offsetWidth + increaseX + 'px'
        target.style.height = target.offsetHeight + increaseY + 'px'
      }
    }
  }
}
</script>

<style scoped>
.box {
  width: 200px;
  height: 200px;
  background-color: pink;
  margin: 0 auto;
  margin-top: 100px;
}
#app {
  width: 800px;
}
</style>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值