我在中间有一组项目(缩略图),悬停时会在侧栏中触发更多信息和大图像。
当我使用下面的代码时,有时 侧边栏中图像的高度为 0。在转到不同的缩略图并返回时正确设置高度。
//this code is run on hover
var maxHeight=140;
$.each(bigimages, function(index,el){
var url = $(this).html(); //each of bigimages class have content of text url
var newli = $('<li><img class="banner-img" src="'+url+'" ></li>');
$(".banner ul").append(newli).promise().done(function(){
console.log("img "+newli.find("img")[0].height); //here sometimes is 0
if(newli.find("img")[0].height>maxHeight){
maxHeight=newli.find("img")[0].height;
}
});
});
编辑
大图像总是存在的,那么为什么这段代码将高度显示为 0?
最佳答案
您将新的 HTML 附加到 ul
元素,但这并不意味着图像会立即加载。如果您在图像的 onload
事件触发之前读取 height
属性,您将得到该值零。考虑将一些代码附加到图像的 onload
事件,并让该代码使用 height
属性。像这样:
//this code is run on hover
var maxHeight = 140;
$.each(bigimages, function(index, el) {
var url = $(this).html(); //each of bigimages class have content of text url
var newli = $('<li><img class="banner-img" src="' + url + '" ></li>');
var image = newli.find("img");
image.on("load", function() {
console.log("img " + $(this)[0].height); //here sometimes is 0
if ($(this)[0].height > maxHeight) {
maxHeight = $(this)[0].height;
}
});
$(".banner ul").append(newli).promise().done(function() {
//anything else you need to do after promise
});
});
关于javascript - 使用 jQuery 插入时并不总是设置图像的高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40985106/