window.onresize的详细使用
创始人
2024-06-01 07:53:33
0次

最近做的项目老是涉及到大小屏切换,但是因为屏幕宽高不一样的原因,老是要计算表格高度

window.onresize:监听window窗口变化,当窗口大小发生变化时,会触发此事件

含义

MDN中的定义是这样子的:

文档视图调整大小时会触发 resize事件。

在js中使用

window.onresize = function(){// todo event
}

在html中使用


在vue中的使用

需要注意的是,this在函数中指的是window,而不是vue实例

mounted(){const _this = thiswindow.onresize = function(){_this.width = document.body.clientWidth// todo event}
}

需要注意的两点:

1、this在函数中不可用,他在函数中不一定指全局上下文

解决办法如下:

const  _this = this
window.onresize = function(){_this.width = document.body.clientWidth
}

2、在谷歌浏览器中,window.onresize会触发两次,网上说是谷歌浏览器的bug

解决办法如下,设定一个标识

	let flag = truewindow.onresize = function () {if (flag) {console.log(new Date(), '窗口改变了')flag = false}let timeId = setTimeout(() => {flag = truetimeId = null // 清除延时定时器}, 1000)}

没使用flag之前

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CutMjFRk-1678451210887)(https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ffb54874-0624-453a-a431-eff7c395a11a/Untitled.png)]

使用之后,如下图,控制台只打印了一遍

在这里插入图片描述

注意在项目中的使用

1、window.onresize只能在一个组件中使用,如果多个组件调用则会出现覆盖情况,所以我的解决方案是在App.vue中使用,获取document.documentElement.clientWidth(即浏览器宽度)存放在vuex中,别的组件只需要用computed(计算属性)将vuex的clientWidth获取,然后通过watch监听clientWidth的值,即可触发组件事件

2、由于window.onresize是全局事件,在其他页面改变界面时也会执行,这样可能会出现问题,需要在出这个界面时注销window.onresize事件。

created() {this.$bus.$on('resize', this.$_setTableHeight)window.onresize = function () {console.log(new Date(), '窗口改变了')}
},
beforeDestroy() {this.$bus.$off('resize', this.$_setTableHeight)window.onresize = null
},

注销之后,切换到其他页面,控制台就不会输出以下信息

在这里插入图片描述

window.addEventListener


mounted() {this.$nextTick(() => {this.onDrawLine()window.addEventListener('resize', this.resize())})},beforeDestroy() {console.log('删除了')// 具名函数使用removeEventListener清除,但是匿名函数不行window.removeEventListener('resize', this.resize())},

性能优化

window.onresize 在监听窗口变化时,固然起到很好的效果,但是对于网页性能消耗过大。因为html中每个标签的变化,都会触发window.onresize 事件,比如显示/隐藏某个抽屉、添加/删除某个div等等,很有可能会造成循环触发和无限制触发,于是新推出了另外一个事件**ResizeObserver(对element和svgelement元素进行监听)**

MDN定义如下:

ResizeObserver避免了通过回调函数调整大小时,通常创建的无限回调循环和循环依赖项。它只能通过在后续的帧中处理 DOM 中更深层次的元素来做到这一点。如果它的实现遵循规范,则应在绘制前和布局后调用 resize 事件。

MDN示例:https://mdn.github.io/dom-examples/resize-observer/resize-observer-text.html

部分源码如下:

const h1Elem = document.querySelector('h1');
const pElem = document.querySelector('p');
const divElem = document.querySelector('body > div');
const slider = document.querySelector('input[type="range"]');
const checkbox = document.querySelector('input[type="checkbox"]');divElem.style.width = '600px';slider.addEventListener('input', () => {divElem.style.width = `${slider.value}px`;
})const resizeObserver = new ResizeObserver((entries) => {for (const entry of entries) {if (entry.contentBoxSize) {// Firefox implements `contentBoxSize` as a single content rect, rather than an arrayconst contentBoxSize = Array.isArray(entry.contentBoxSize) ? entry.contentBoxSize[0] : entry.contentBoxSize;h1Elem.style.fontSize = `${Math.max(1.5, contentBoxSize.inlineSize / 200)}rem`;pElem.style.fontSize = `${Math.max(1, contentBoxSize.inlineSize / 600)}rem`;} else {h1Elem.style.fontSize = `${Math.max(1.5, entry.contentRect.width / 200)}rem`;pElem.style.fontSize = `${Math.max(1, entry.contentRect.width / 600)}rem`;}}console.log('Size changed');
});resizeObserver.observe(divElem);checkbox.addEventListener('change', () => {if (checkbox.checked) {resizeObserver.observe(divElem);} else {resizeObserver.unobserve(divElem);}
});

副作用:兼容性不强,有些浏览器兼容,具体情况见Can I Use

参考链接:

https://www.cnblogs.com/yxysuanfa/p/6878016.html

https://www.jb51.net/article/245030.htm

https://developer.mozilla.org/zh-CN/docs/Web/API/ResizeObserver

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...