首页 > 解决方案 > Chrome Resize 事件和 getComputedStyle

问题描述

我对调整大小事件和 getComputedStyle 方法有疑问。当我将窗口大小从例如 700 像素调整到 800 像素以上时,我的元素高度从 79 像素变为默认值(10 像素)。但是当我想通过 getComputedStyle 获取这个值(10px)或在 devtools 中检查它时,会输出如下内容:76、63、59,最后是 10px。所以 devtools 中的高度值在下一个调整大小事件时更新,而不是第一次更新,并且每个调整大小事件之间都有一些中间值。所以我的问题是,我怎样才能得到最终的价值?我尝试使用 setTimeout 方法调整大小,但这也无法按预期工作。我的代码看起来像这样:

window.addEventListener("DOMContentLoaded", function(){
    if(window.matchMedia("(min-width:800px)").matches){
        default();  
    }
    else{
        changeHeight();
    }
    window.addEventListener('resize',onResizeFunction);


})
function default(){
    slot.parentElement.style.height=''
    console.log(slot.parentElement.style.height) 
    console.log(getComputedStyle(slot.parentElement).height)  //problem with this line, when called in resize event it's output something like this: 76,63,59 and then 10px;

}

function changeHeight(){
    slot.parentElement.style.height="79px";
    console.log(slot.parentElement.style.height)  //this is ok

}

function onResizeFunction(){

    if(window.matchMedia("(min-width:800px)").matches){
        default();
    }
    else{
        changeHeight();
    }

}

而且我不能使用 CSS,因为我正在做一个旧项目,只能使用 JS 来完成这项工作

标签: javascripthtmlcssresize

解决方案


请为您的 dom 提供您的 css,我打赌您有一些过渡


推荐阅读