本文主要是介绍【前端开发】可拉动宽度窗口,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 组件:Resize
<template><div :style="{width: defaultWidth + 'px', position: 'relative'}"><div ref="container" class="d-flex"><div style="width: 100%; height: 100vh;"><!-- 显示内容主体--><slot name="body"></slot></div></div><!-- 拖拽条 --><div v-if="resizeShow" class="resize" @mousedown.stop="onMouseDown" @mouseup.stop="onMouseup"/></div></template><script>
export default {props: {// 控制拖拽条的是否显示,默认显示resizeShow: {type: Boolean,default: true}},data() {return {defaultWidth: 240,beforeWidth: 0,afterWidth: 0}},methods: {// 按下鼠标开始监听鼠标移动事件onMouseDown(e) {this.beforeWidth = e.clientXdocument.addEventListener('mousemove', this.onMousemove)document.addEventListener('mouseup', this.onMouseup)e.preventDefault()},// 监听鼠标移动 实现盒子宽度变化onMousemove(e) {this.afterWidth = e.clientX// 根据鼠标位置判断向左还是向右拖动if (this.beforeWidth < this.afterWidth) {this.defaultWidth = this.defaultWidth + (this.afterWidth - this.beforeWidth)this.beforeWidth = e.clientX} else {this.defaultWidth = this.defaultWidth - (this.beforeWidth - this.afterWidth)this.beforeWidth = e.clientX}},onMouseup(e) {e.preventDefault()// 松开鼠标后移除监听document.removeEventListener('mousedown', this.onMouseDown)document.removeEventListener('mousemove', this.onMousemove)}}
}</script><style>
.d-flex {display: inline-block;overflow: hidden;width: 100%;
}.resize {position: absolute;top: 0;right: 1px;display: inline-block;width: 20px;height: 100%;cursor: col-resize;margin: 0 1px;
}
</style>
2. JavaScript调用组件
<template><div class="app-box"><ResizeBox :resizeShow="resizeShow"/></div>
</template>
<script>
import ResizeBox from './components/ResizeBox/index.vue';
export default {data(){return{resizeShow:true //是否可拖动修改宽度}},components:{ResizeBox}
}
</script>
<style scoped>
.app-box {display: flex;
}
</style>
3. TypeScript调用组件
<template><div class="app-box"><ResizeBox :resizeShow="resizeShow"/></div>
</template>
<script setup lang="ts">
import ResizeBox from './components/ResizeBox/index.vue';//是否可拖动改变宽度
let resizeShow = true;
</script>
<style scoped>
.app-box {display: flex;
}
</style>
这篇关于【前端开发】可拉动宽度窗口的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!