以下基于vue3 来实现
首先创建一个指令函数页面 sizeDriect.js
const map = new WeakMap() //相对map 不会造成内存泄漏 const ob = new ResizeObserver((entries) => { for(const entry of entries){ //处理对应元素的回调 const handler = map.get(entry.target) if(handler){ const box = entry.borderBoxSize[0] handler({ width: box.inlineSize, height: box.blockSize }) } } }) export default { mounted(el, binding){ //监视尺寸变化 ob.observe(el) map.set(el, binding.value) }, unmounted(){ //取消监听 ob.unobserve(el) } }
import sizeDriect from './sizeDriect' app.directive('size-ob', sizeDriect) //全局引用注册即可
在页面使用方式
<div class="maintain" v-size-ob="hanleSizeChange"> </div> const hanleSizeChange = (size) => { console.log(size) } 打印结果 :{width: 863.09375, height: 837.734375}
标签:map,const,自定义,el,ob,指令,尺寸,sizeDriect,size From: https://www.cnblogs.com/xuhuang/p/17269054.html