【发布时间】:2020-11-13 22:35:12
【问题描述】:
我尝试按横向/纵向格式对图像进行排序,为此我首先使用 selectFunction() 选择页面上的所有图像,然后使用触发进一步操作的函数“hochquer”对它们进行排序。
我的问题: 一个图像在 console.log() 中显示的宽度和高度为 0,即使它正确显示在我的页面上并且具有实际的宽度和高度。如果我第二次重新加载页面,它工作得很好,我得到了这个图像的宽度和高度。
谁能帮我解决这个问题?
//Screenshot of the console added
function selectFunction() {
img = document.querySelectorAll(".img");
let imgSelector = Array.from(img);
if (imgSelector % 2 != 0) {
imgSelector.push("even'er");
}
return imgSelector;
}
function hochquer(callback) {
for (let i = 0; i < selectFunction().length; i++) {
console.log(selectFunction()[i]);
let Width = selectFunction()[i].naturalWidth;
console.log(Width, "w");
let Height = selectFunction()[i].naturalHeight;
console.log(Height, "h");
let Ratio = Width / Height;
if (Ratio >= 1) {
//quer
querFormat.push(selectFunction()[i]);
} else {
querFormat.push(undefined);
}
if (Ratio < 1) {
//hoch
hochFormat.push(selectFunction()[i]);
} else {
hochFormat.push(undefined);
}
}
callback();
}
更新:
-
控制台截图: [1]:https://i.stack.imgur.com/Jr6P8.png
-
我使用的更多代码解决了@54ka 提到的问题
function newImg() {
let createImg = [];
let imgSrc = [];
const imgContainer = document.querySelector(".gallery");
for (let i = 0; i < Gallery.length; i++) {
createImg.push(new Image());
imgSrc.push(Pfad + Gallery[i]);
createImg[i].setAttribute("src", imgSrc[i]);
createImg[i].setAttribute("class", "Img");
imgContainer.appendChild(createImg[i]);
function checkImage(path) {
return new Promise((resolve) => {
createImg[i].onload = () => resolve({ path, status: "ok" });
createImg[i].onerror = () => resolve({ path, status: "error" });
});
}
loadImg = function (...path) {
return Promise.all(path.map(checkImage));
};
}
loadImg(imgSrc).then(function (result) {
console.log(result);
hochquer(sort);
});
}
newImg();
【问题讨论】:
-
你能告诉我们用户界面和控制台吗,比如截图?
-
原因是第一次加载的时候,从一张还没有加载的图片中取一个尺寸。在刷新浏览器中,它会将其放下并设法在脚本通过之前将其显示出来。要解决此问题,请添加“onload 事件”,例如: 或尝试此链接:Javascript - execute after all images have loaded
-
感谢您的快速回复。我添加了一个屏幕截图并更新了代码 + 显示了一个新示例,我认为它已经解决了@54ka 提到的问题。
-
@链接完成_____
-
请看我的回答,这不是您问题的解决方案,但我需要您运行我回答中的代码,如果宽度和高度仍然显示不正确,请告诉我。跨度>
标签: javascript image