基于vue手写一个分屏器,通过鼠标控制屏幕宽度。
先来看看实现效果:
QQ录屏20220403095856
下面是实现代码:
<template><section class="section"><div class="left" ref="left">这是左边的div<div class="box" ref="box"></div></div><div class="right" ref="right">这是右边的div</div></section>
</template><script>
export default {name: 'Test',mounted() {this.init()},methods: {init() {let left = this.$refs.leftlet right = this.$refs.rightlet box = this.$refs.box// firstX鼠标开始坐标位置,endX鼠标结束坐标位置,startWidth左边div开始宽度let firstX, endX, startWidthfunction myFunction(e) {// 划过左边线endX = e.clientX - firstX// 获取移动的距离left.style.width = startWidth + endX + 'px'}function selectStart(flag) {left.onselectstart = function() {return flag}right.onselectstart = function() {return flag}}box.addEventListener('mousedown',function(e) {// 当鼠标点击移动开始不选中div里的内容selectStart(false)startWidth = left.offsetWidth // 起始宽firstX = e.clientX // 起始点document.addEventListener('mousemove',myFunction) // 开始移动})box.addEventListener('mouseleave',function(e) {document.removeEventListener("mousemove", myFunction) // 结束移动})document.addEventListener('mouseup', function() {// 当鼠标点击移动结束恢复选中div里的内容selectStart(true)// 移除移动事件,注意:移除事件的回调函数必须和注册事件是同一个,要不然移除不了哦!document.removeEventListener("mousemove", myFunction) // 结束移动})}}
}
</script>
<style lang="scss" scoped>* {margin: 0;padding: 0;}.section {width: 100%;height: 100%;display: flex;}div.right {background-color: #00B83F;height: 100%;flex: 1;}div.left {width: 200px;background-color: #FFB951;z-index: 1;height: 100%;position: relative;.box {width: 50px;height: 50px;cursor: col-resize;background: red;position: absolute;right: 0;top: 0;bottom: 0;margin: auto;}}
</style>