vue3 input上边框拖拽 改变宽度

模仿微信聊天框 下面聊天input框 输入过多时 可以拖拉input上边框进行放大

首先先了解一下 vue的鼠标mouse几个事件

@mousedown  鼠标按下

@mousemove 鼠标移动

@mouseup 鼠标松开

@mouseleave 鼠标离开

 当鼠标按下mousedown  时,会调用startDrag方法开始拖拽。首先我们记录元素的初始位置startY和input框的初始高度startHeight。然后鼠标移动mousemove时记录鼠标达到地方跟初始位置的偏移量offsetY,用初始高度startHeight加上这个偏移量offsetY就得到拖拽后的高度。

注意:鼠标移开的时候要移除对鼠标事件的监听

<template>
  <div>
    <ul :style="{height: 'calc(100% - '+inputHeight+'px)'}">
      <li v-for="i in 19">消息消息</li>
    </ul>
    <input
      class="inputElement"
      ref="inputElement"
      v-model="inputValue"
      :style="{
        width: inputWidth + 'px',
        height: inputHeight + 'px',
      }"
      @mousedown="startDrag"
      @mouseup="endDrag"
    />
  </div>
</template>

<script>
import { Loading } from "@element-plus/icons-vue";
import { ref } from "vue";

export default {
  setup() {

    const inputValue = ref("");
    const isDragging = ref(false);
    const startY = ref(0);
    const startHeight = ref(0);
    const inputWidth = ref(200); // 设置初始宽度
    const inputHeight = ref(100); // 设置初始宽度

    const startDrag = (event) => {
      isDragging.value = true;
      startY.value = event.clientY;
      startHeight.value = inputHeight.value;
      document.addEventListener("mousemove", dragging);
      document.addEventListener("mouseup", endDrag);
    };

    const dragging = (event) => {
      if (isDragging.value) {
        // 上边框移动
        const offsetY =  startY.value-event.clientY;
        const newWidth = Math.max(startHeight.value + offsetY, 20); // 设置最小宽度
        inputHeight.value = newWidth;
      }
    };

    const endDrag = () => {
      isDragging.value = false;
      document.removeEventListener("mousemove", dragging);
      document.removeEventListener("mouseup", endDrag);
    }
    
    return {
      inputValue,
      inputWidth,
      inputHeight,
      startDrag,
      endDrag
    };
  },
};
</script>
<style lang="less" scoped>
div {
  height: 400px;
  width: 200px;
  ul {
    height: calc(100% - 100px);
    overflow-y: scroll;
    background: #fff;
  }
  .inputElement {
    outline: none;
  }
}
</style>

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值