为什么元素的宽度在页面加载之后和那一刻之后不同

why the width of elements are different after page load and after that moment?

本文关键字:之后 加载 那一刻 元素 为什么      更新时间:2023-09-26

情况是,我想在页面加载后立即更改元素的大小。问题是元素没有改变,因为函数getSearchBarWidth返回的结果是负数。奇怪的是,控制台打印两个元素web_logomenu的宽度值不正确;它们的宽度应该很小,但在控制台中,两个元素的宽度都等于父元素,即导航栏。但后来,我在控制台中再次打印出两个元素的宽度,结果是正确的。有人能解释一下吗?

更新:这似乎是因为我没有指定导航栏的宽度。那么,除了指定父元素的宽度以在页面加载后立即获得其子元素的正确宽度之外,还有其他方法吗?

 <script src="js/function.js" defer></script>

js 文件的内容

// calculate the width of window and relevant element
function getSearchBarWidth(){
    var wWidth = $(window).width();
    var offset = 20; // distance between the search bar and each of the two next elements
    var offset_1 = 15; // padding of each sides of the navi bar
    var searchBarWidth = wWidth - $("#navi_bar > .web_logo").width() - $("#navi_bar > .menu").width() - 2*offset - 2*offset_1;
    return searchBarWidth;
}
// change the size of search bar
if($("#navi_bar > .search_bar").length > 0){
    console.log("window: "+ $(window).width());
    console.log("logo: "+ $("#navi_bar > .web_logo").width());
    console.log("menu: "+ $("#navi_bar > .menu").width());
    $("#navi_bar > .search_bar").css("width", getWindowWidth());    
}

我的问题解决了。只要调用setTimeout,元素的宽度就会正确。