我是靠谱客的博主 能干朋友,最近开发中收集的这篇文章主要介绍vue鼠标控制元素缩放和拖拉拽效果demo,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

<template>
  <div class="home" ref="back_box">
      <div 
        class="box"
        draggable="true"
        @dragstart="dragStart($event)"
        @dragend="dragEnd($event)"
        @wheel="handlewheel"
        :style="`left:${elLeft}px;top:${elTop}px;width:${elWidth}px;height:${elHeight}px;`"
        >
        <div class="text" :style="`left:${(0*this.elWidth)/100}px;top:${(25*this.elHeight)/100}px; transform:scale(${meter_zoom})`">这是一个可以缩放和拖拉拽的盒子</div>
        </div>
  </div>
</template>

<script>
// @ is an alias to /src
export default {
  name: 'HomeView',
  data(){
    return {
      initWidth:0, // 父元素的宽
      initHeight:0, // 父元素的高
      startclientX:0,
      startclientY:0,
      elLeft:0,
      elTop:0,
      zoom:1,//缩放比例
      elWidth:0, // 元素宽
      elHeight:0, // 元素高
      meter_zoom: 0, // 子元素的缩放比例
    }
  },
  methods:{
    // 拖拽开始时间
    dragStart(e){
      console.log(e);
      // 记录元素拖拽初始位置
      this.startclientX = e.clientX;
      this.startclientY = e.clientY;
    },
    // 拖拽完成事件
    dragEnd(e){
      console.log(e);
      // 计算偏移量
      this.elLeft += e.clientX - this.startclientX;
      this.elTop += e.clientY - this.startclientY;
    },
    // 页面初始化
    initBodySize(){
      this.initWidth = this.$refs.back_box.clientWidth;
      this.initHeight = this.initWidth * (1080/1920);
      this.elWidth = this.initWidth * (100/(1920/2)); // 元素宽 元素初始宽度/父元素如果是50vw就是1920/2
      this.elHeight = this.initHeight * (100/(1080/2)); // 元素高 元素初始高度/父元素如果是50vh就是1080/2
      this.meter_zoom = this.elWidth/100 // 子元素的缩放比例
    },
    // 鼠标滚轮事件
    handlewheel(e){
      if(e.wheelDelta < 0){
        this.zoom -= 0.05
      }else{
        this.zoom += 0.05
      }
      // 如果放大超过3 就限制 不能一直放大
      if(this.zoom >= 3){
        this.zoom  = 3;
        alert('已放至最大')
        return;
      }
      // 同理 缩小也是
      if(this.zoom <= 1){
        this.zoom = 1;
        alert('已放至最小')
        return;
      }
      this.elWidth = this.initWidth * (100/(1920/2)) * this.zoom;
      this.elHeight = this.initHeight * (100/(1080/2)) * this.zoom;
      this.meter_zoom = this.elWidth/100
    }
  },
  mounted(){
    this.initBodySize();
  }
}
</script>
<style scoped lang="less">
  *{
    margin: 0;
    padding: 0;
  }
.home{
  background-color: #ccc;
  width: 50vw;
  height: 50vh;
  position: relative;
  .box{
    width: 100px;
    height: 100px;
    user-select: none;
    background: blue;
    position: absolute;
    z-index: 2;
    .text{
      width: 100px;
      height: 100px;
      transform-origin: 0 0;
      font-size: 16px;
      position: absolute;
    }
  }
}
</style>

最后

以上就是能干朋友为你收集整理的vue鼠标控制元素缩放和拖拉拽效果demo的全部内容,希望文章能够帮你解决vue鼠标控制元素缩放和拖拉拽效果demo所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部