当前位置:网站首页>拖动元素边缘改变宽度
拖动元素边缘改变宽度
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>
边栏推荐
猜你喜欢
随机推荐
MIPI解决方案 ICN6202:MIPI DSI转LVDS转换芯片
unity学习(一):自动化创建模板脚本
字符串哈希
【多线程】线程安全保护机制
Mac安装MySQL详细教程
GM8775C MIPI转LVDS调试资料分享
剑指Offer 47.礼物的最大值 动态规划
如何使用 PHP 实现网页交互
联阳IT6561|IT6561FN方案电路|替代IT6561方案设计DP转HDMI音视频转换器资料
发布全新的配置格式 - AT
proteus数字电路仿真——入门实例
2019 - ICCV - 图像修复 Image Inpainting 论文导读《StructureFlow: Image Inpainting via Structure-aware ~~》
同时求最大值与最小值(看似简单却值得思考~)
剑指Offer 35.复杂链表的复制
install 命令
LL(1)文法 :解决 if-else/if-else 产生式二义性问题
【LeetCode】求和
【LeetCode】Add the linked list with carry
读取FBX文件踩坑清单
哈希表解题方法