模仿微信聊天框 下面聊天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>