javascript - 包含元素的宽度未正确显示
问题描述
几个图像被放置到一个显示为 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 来获取宽度。请帮助解决这个问题。
代码已上传到这里的代码框
解决方案
所以我为您的问题创建了一个解决方案:并确保添加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);
希望我能帮上忙。
推荐阅读
- batch-file - 从批处理文件向 SQL 传递参数 - 出现垃圾值
- android - 比较方法违反了它的总合同!排序时
- node.js - 来自 Lambda 的 AWS 开发工具包调用需要超过 30 秒
- mysql - 如何编写 SQL 查询以查找超过百分比平均值?
- html - 将自定义箭头放在自定义下拉列表的顶部
- javascript - react中箭头函数的优化
- excel - 填充用户表单标签
- docker - 如何在 docker 容器内 REPL uberjar?
- php - 如何在我的本地主机上用 PHP 正确设置谷歌云视觉?
- java - Shiro's clearCachedAuthenticationInfo is null