當我單擊瀏覽器窗口的最大化按鈕時,我編寫的一個將在調整窗口大小時執行的函數無法正常工作,我認為是因為 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!
JavaScript 窗口大小調整事件很慢。如何優化窗口調整大小事件
料青山看我應如是
2021-05-31 18:54:57