首页 > 解决方案 > 包含元素的宽度未正确显示

问题描述

几个图像被放置到一个显示为 flex 并且 flex-wrap 设置为 nowrap 的元素中。图像不适合元素的宽度并超出屏幕宽度。

我正在尝试计算包含图像的元素的宽度。然而,元素的宽度总是等于屏幕宽度,而它应该比屏幕宽度大得多。

有几个线程建议首先检查所有图像是否已加载。以下是用于检查图像加载的代码。

let len = allCarousalImagesList.length,
    counter = 0;

[].forEach.call( allCarousalImagesList, function( img ) {
    if(img.complete)
      incrementCounter();
    else
      img.addEventListener( 'load', incrementCounter, false );
} );

function incrementCounter() {
    counter++;
    if ( counter === len ) {
        let carousalWidth = carousalElement.offsetWidth;
        let browserWidth = window.innerWidth;
        console.log(browserWidth, carousalWidth);
    }
}

尽管检查了图像的加载,但包含展开图像的元素的宽度未正确显示并且等于屏幕宽度。我正在使用 offsetWidth 来获取宽度。请帮助解决这个问题。

代码已上传到这里的代码框

标签: javascripthtmlcss

解决方案


所以我为您的问题创建了一个解决方案:并确保添加position:absolute; 去你的狂欢课

   window.addEventListener("load", function () {
      let carousalElement = document.getElementsByClassName("carousal")[0];
      var width_of_img_container = window.getComputedStyle(carousalElement).width;
      console.log(width_of_img_container);
    },false);

希望我能帮上忙。


推荐阅读