为了账号安全,请及时绑定邮箱和手机立即绑定

JavaScript 窗口大小调整事件很慢。如何优化窗口调整大小事件

JavaScript 窗口大小调整事件很慢。如何优化窗口调整大小事件

料青山看我应如是 2021-05-31 18:54:57
当我单击浏览器窗口的最大化按钮时,我编写的一个将在调整窗口大小时执行的函数无法正常工作,我认为是因为 JavaScript 窗口调整大小事件运行缓慢。当我使用鼠标调整窗口大小时,它起作用了。此外,当我尝试在纵向移动和横向移动之间切换时,它也很慢。使用 window.addEventListener('resize', aFunction) 时遇到问题,页面变慢。这些事件每秒生成多次,如果事件处理程序花费太多时间,浏览器将无法重绘页面。<div class="div1">    <div class="div2"></div></div>.div1 { position: relative; }.div2 { position: absolute; width: 300px; top: 0; transition: all 0.5s ease; }@media only screen and (max-width: 1024px) { .div2 { width: 200px; } }function aFuntion() {    let div1 = document.querySelector('.div1');    let div2 = document.querySelector('.div2');    let diff = div1.clientHeight - div2.clientHeight;    div2.style.top = diff + 'px';};// Call the function.// This worked!aFuntion();// Call the function when users resize the window.// This worked!window.addEventListener('resize', aFuntion);// Users click on the Maximize button of the window.// The function does not work properly!// Portrait mobile to Landscape mobile.// The function does not work properly!
查看完整描述

3 回答

?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

我删除了过渡:所有 0.5 秒的缓和;它工作了一段时间,现在它不再工作了。

所以,我现在知道这是因为 window.addEventListener('resize', function) 运行缓慢。


查看完整回答
反对 回复 2021-06-03
?
慕运维8079593

TA贡献1876条经验 获得超5个赞

尝试 document.addEventListener('resize', aFuntion);


查看完整回答
反对 回复 2021-06-03
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

我已经在 Firefox、Chrome 和 Internet Explorer 中测试了下面的代码,它按预期工作。我知道这是一种解决方法,因为该事件是从 body 标签触发的,但也许它会对您有所帮助。


<html>

<head>

<script>

function resizeFunction() {

    console.log("working");

}

</script>

</head>

<body onresize="resizeFunction()">

content

</body>

</html>


查看完整回答
反对 回复 2021-06-03
  • 3 回答
  • 0 关注
  • 190 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信