当前位置:网站首页>拖动元素边缘改变宽度
拖动元素边缘改变宽度
2022-08-02 03:34:00 【IICOOM】
最近有个需求,需要可以手动拖动侧边栏菜单,改变其宽度。如下:

要完成这个功能,我们需要了解以下前端知识:
- 鼠标按下、抬起事件(mousedown、mouseup)
- 鼠标移动事件(mousemove)
- 鼠标按下时在屏幕上的位置 clientX
- 鼠标hover到元素上鼠标样式
- 为了使调整过程比较顺滑,需要用到css transition
好,差不多了,开整。
添加页面元素
<template>
<div class="m_wrapper">
<div class="left">
<div class="side_bar">
Side Menu
<div class="handle"></div>
</div>
</div>
<div class="right">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dignissimos error illum laboriosam laudantium natus quaerat tempora voluptatibus! Beatae dolor doloribus ex facere, iste iure maiores perferendis perspiciatis qui vel. Eligendi?</div>
</div>
</template>
添加元素样式
<style scoped>
.m_wrapper {
display: flex;
padding: 10px;
user-select: none;
}
.m_wrapper .side_bar {
width: 250px;
height: 300px;
background-color: rgba(13, 202, 240, 0.32);
position: relative;
transition: width linear 100ms;
box-sizing: border-box;
}
.m_wrapper .right {
margin-left: 10px;
border: 1px solid #ccc;
}
.handle {
height: 100%;
width: 2px;
position: absolute;
right: -1px;
top: 0;
transition: all linear 200ms;
}
.handle:hover {
background-color: #4578FF;
cursor: col-resize;
}
</style>
添加鼠标移动逻辑
<script>
export default {
name: "MouseMove",
mounted() {
let th = this
// 通过鼠标按下事件来监听鼠标移动事件
document.addEventListener('mousedown', function (e) {
th.x = e.clientX
document.addEventListener('mousemove', th.move)
})
document.addEventListener('mouseup', function () {
document.removeEventListener('mousemove', th.move)
})
this.target = document.querySelector('.side_bar')
},
data() {
return {
target: '',
x: '',
}
},
methods: {
move(e) {
if (e.clientX - this.target.offsetLeft> 400) {
this.target.style.width = '400px'
} else if (e.clientX - this.target.offsetLeft<200) {
this.target.style.width = '200px'
} else {
this.target.style.width = e.clientX - this.target.offsetLeft + 'px'
}
},
}
}
</script>
边栏推荐
- Basic IO (below): soft and hard links and dynamic and static libraries
- path 修补文件命令
- MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
- 2020 - AAAI - 图像修复 Image Inpainting论文导读 -《Region Normalization for Image Inpainting》
- LL(1)文法 :解决 if-else/if-else 产生式二义性问题
- Industry where edge gateway strong?
- 剑指Offer 32.Ⅲ从上到下打印二叉树
- “520” 如何正确地用代码向 ta 表白?
- 【LeetCode】链表相加 进位
- 学习(四):显示FPS,和自定义显示调试
猜你喜欢
随机推荐
龙讯LT6911系列C/UXC/UXB/GXC/GXB芯片功能区别阐述
MQ-5 combustible gas sensor interface with Arduino
模拟电子技术------半导体
【nRF24L01 connects with Arduino to realize wireless communication】
IDEA2021.2安装与配置(持续更新)
rosdep update失败解决办法(亲测有效)
Lightly:新一代的C语言IDE
bluez5.50+pulseaudio实现蓝牙音响音频播放
增量编译技术在Lightly中的实践
改变文件的扩展名
Beckhoff ET2000 listener use
TeamCode 产品 UI 全新升级,快来体验吧
Industry where edge gateway strong?
剑指Offer 31.栈的压入、弹出
调试九法准则
引擎开发日志:重构骨骼动画系统
倒排单词
DMA相应外设映射
使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
如何搭建私有云盘?









