完整代码:
<template>
<div class="row-box">
<div class="column-box">
<div class="content-box">
<slot></slot>
</div>
</div>
</div>
</template>
<script>
export default {
name: "xScroll",
data() {
return {
sizeInfo: {
x: 0,
y: 0,
},
};
},
mounted() {
// this.sizeInfo.x = dom.clientHeight;
// this.sizeInfo.y = dom.clientWidth;
const observer = new ResizeObserver((entries) => {
const obj = entries[0];
const { width, height } = obj.contentRect;
this.sizeInfo.x = height;
this.sizeInfo.y = width;
});
const dom = document.querySelector(".row-box");
observer.observe(dom);
},
methods: {
handleSizeChange() {
const dom = document.querySelector(".row-box");
this.sizeInfo.x = dom.clientHeight;
this.sizeInfo.y = dom.clientWidth;
},
},
};
</script>
<style lang="less" scoped>
.row-box {
// width: 1180px;
width: 80%;
height: 470px;
}
.column-box {
position: relative;
width: calc(v-bind("sizeInfo.x") * 1px);
height: calc(v-bind("sizeInfo.y") * 1px);
background-color: blanchedalmond;
transform: translateY(calc(v-bind("sizeInfo.x") * 1px)) rotate(-90deg);
transform-origin: 0 0;
overflow: auto;
scrollbar-width: none;
}
.column-box::-webkit-scrollbar {
width: 0;
}
.content-box {
height: calc(v-bind("sizeInfo.x") * 1px);
position: absolute;
left: 100%;
transform: rotate(90deg);
transform-origin: 0 0;
}
</style>
ResizeObserver
ResizeObserver 构造函数创建一个新的 ResizeObserver 对象,它可以用于监听元素内容盒或边框盒或者尺寸的大小
new ResizeObserver(callback)
function callback(entries, observer) {
for (const entry of entries) {
// Do something to each entry
// and possibly something to the observer itself
}
}
entries是一个数组,可以用于获取每个元素改变后的新尺寸
observer 对 resizeObserver 自身的引用,因此需要它的时候,你要从回调函数的内部访问。例如,这可用于在达到特定的情况时,自动取消对观察者的监听
resizeObserver.observe(divElem); // 开始对指定元素的监听
resizeObserver.unobserve(divElem,options);// 结束对指定元素的监听,options可以设置监听的盒模型
resizeObserver.disconnect() // 取消特定观察者目标上所有对 Element 的监听