ResizeObserver
ResizeObserver 接口可以监听到 Element 的内容区域或 SVGElement的边界框改变。内容区域则需要减去内边距padding。(有关内容区域、内边距资料见盒子模型 )
换句话来说,ResizeObserver是可以监听到DOM元素,宽高的变化,需要注意的一点就是监听出变化结果是contentBox的宽度和高度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Static Template</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
border: 2px solid red;
font-size: 40px;
user-select: none;
position: relative;
padding: 10px;
}
button {
width: 100px;
height: 40px;
margin: 10px 0;
}
</style>
</head>
<body>
<div class="box1 box">box1</div>
<div class="box2 box">box2</div>
<button class="btn1">取消box1的监听</button>
<button class="btn2">取消所有的监听</button>
<script>
const resizeObserver = new ResizeObserver((entries, b) => {
for (let entry of entries) {
console.log(entries, b === resizeObserver);
}
});
const elbox1 = document.querySelector(".box1");
const elbox2 = document.querySelector(".box2");
resizeObserver.observe(elbox1);
resizeObserver.observe(elbox2);
elbox2.onclick = elbox1.onclick = function(e) {
e.target.style.width = e.target.offsetWidth + 10 + "px";
};
const elbtn1 = document.querySelector(".btn1");
const elbtn2 = document.querySelector(".btn2");
elbtn1.onclick = function() {
resizeObserver.unobserve(elbox1);
};
elbtn2.onclick = function() {
resizeObserver.disconnect();
};
</script>
</body>
</html>
实际用途
- 配合echarts进行使用
在echarts中我们往往会把图表放进某个div容器,如果你只是通过window.onresize是无法监听到容器的变化,从而使得图表自适应。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#main{
border: 1px solid red;
}
</style>
<script src="https://cdn.bootcdn.net/ajax/libs/echarts/5.3.2/echarts.js"></script>
</head>
<body>
<div id="main" style="width: 600px;height:400px;"></div>
<button id="big">放大</button>
<script>
let main = document.getElementById('main')
var myChart = echarts.init(main);
let oBig = document.getElementById("big")
const resizeObserver = new ResizeObserver((entries, b) => {
myChart.resize()
});
resizeObserver.observe(main)
var option = {
title: {
text: 'ECharts 入门示例'
},
tooltip: {},
legend: {
data: ['销量']
},
xAxis: {
data: ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子']
},
yAxis: {},
series: [
{
name: '销量',
type: 'bar',
data: [5, 20, 36, 10, 10, 20]
}
]
};
oBig.onclick = ()=>{
main.style.width = 1000+"px"
}
myChart.setOption(option);
</script>
</body>
</html>
- 自定义滚动条
可参考elementUI中的el-scrollbar 实现过程
|