功能需求:页面左右布局,左边初始定宽512px,右侧宽度 flex:1,分割线中间有拖拽按钮,拖拽时 左侧的宽度最大宽度是现在宽度+现在宽的的50%。最小宽度是初始宽度的一半 。
解决思路:在mounted生命周期,监听分割线DOM的onmousedown事件,在拖拽过程中动态计算,然后赋值改变左右DOM元素的宽度。
实现代码:(class类里用的tailwindcss)
左侧内容区
{this.envHost && }
{!this.envHost &&
.subject__left_container {
width: 512px;
border-right: 1px solid #e8e8e8;
}
// mounted生命周期
public mounted() {
this.leftDom = this.$refs.leftDom;
let moveDom = this.$refs.moveDom;
(moveDom as any).onmousedown = (e: any) => {
this.clientStartX = e.clientX;
e.preventDefault();
document.onmousemove = (e) => {
this.moveHandle(e.clientX, this.leftDom);
};
document.onmouseup = () => {
document.onmouseup = null;
document.onmousemove = null;
};
};
}
public moveHandle(nowClientX: number, letfDom: any) {
let computedX = nowClientX - this.clientStartX;
let leftBoxWidth = parseInt(letfDom.clientWidth);
let changeWidth = leftBoxWidth + computedX;
if (changeWidth < 256) {
changeWidth = 256;
}
if (changeWidth > 768) {
changeWidth = 768;
}
letfDom.style.width = changeWidth + 'px';
this.clientStartX = nowClientX;
}
注意: 以上代码对左右布局都是div的话 是ok的,但是当我们右边的布局里有iframe,单纯这么写,拖拽时鼠标移入右侧iframe区时会拖不动,或者无法根据鼠标移动,快速响应,甚至在监听鼠标的按下和松开事件上都有明显的卡顿问题。
解决方法:在拖动的时候,在iframe上方添加一个透明的遮罩层,然后在停止拖拽的时候让其消失。
左侧内容区
{this.envHost && }
{!this.envHost &&
.subject__left_container {
width: 512px;
border-right: 1px solid #e8e8e8;
}
.iframe__div {
width:100%;
height: 100%;
position: absolute;
z-index: 999;
filter: alpha(opacity=0);
opacity: 0;
background: transparent;
display: none;
}
// mounted生命周期
public mounted() {
this.leftDom = this.$refs.leftDom;
let moveDom = this.$refs.moveDom;
var iframeDiv = this.$refs.iframeDiv;
(moveDom as any).onmousedown = (e: any) => {
this.clientStartX = e.clientX;
e.preventDefault();
if (iframeDiv) {
(iframeDiv as any).style.display = 'block';
}
document.onmousemove = (e) => {
this.moveHandle(e.clientX, this.leftDom);
};
document.onmouseup = () => {
if (iframeDiv) {
(iframeDiv as any).style.display = 'none';
}
document.onmouseup = null;
document.onmousemove = null;
};
};
}
public moveHandle(nowClientX: number, letfDom: any) {
let computedX = nowClientX - this.clientStartX;
let leftBoxWidth = parseInt(letfDom.clientWidth);
let changeWidth = leftBoxWidth + computedX;
if (changeWidth < 256) {
changeWidth = 256;
}
if (changeWidth > 768) {
changeWidth = 768;
}
letfDom.style.width = changeWidth + 'px';
this.clientStartX = nowClientX;
}