我有一个非常可悲的西红柿,因为它没有调整大小,可怜的东西。如果我不使用"load“函数,那么我的一些拇指就不会调整大小,如果我这样做了,那么其他拇指就不会调整大小。
startDiv.find('img').each(function(p) {
$(this).parent().css({ height: thumbs_size, width:thumbs_size });
$(this).css({ height: thumbs_size, width: thumbs_size }); //temporary
$(this).load(function() {
if ($(this).height() > $(this).width()) {
var w = thumbs_size;
var h = Math.ceil($(this).height() / $(this).width() * thumbs_size);
} else {
var h = thumbs_size;
var w = Math.ceil($(this).width() / $(this).height() * thumbs_size);
}
$(this).css({ height: h, width: w });
});
});有人能救我的西红柿吗?谢谢!:)
发布于 2012-07-18 03:01:12
这是因为当您调用$(this).load(时,可能已经加载了一些。执行以下操作,或类似的操作
startDiv.find('img').each(function(p) {
$(this).parent().css({ height: thumbs_size, width:thumbs_size });
$(this).css({ height: thumbs_size, width: thumbs_size }); //temporary
var $this = $(this);
function onLoad() {
var height = $this.height(), width = $this.width();
var isPortrait = height > width;
var w = isPortrait ? thumbs_size : Math.ceil(width / height * thumbs_size);
var h = isPortrait ? Math.ceil( height / width * thumbs_size) : thumbs_size;
$this.css({ height: h, width: w });
}
// Set it on the load event handler in case it's not loaded
// If it has a width, it's already loaded
if ($(this).width() > 0) {
onLoad();
} else {
$this.load(onLoad);
}
});或者您可以在onload处理程序中使用它,该处理程序保证DOM中的所有图像(以及所有脚本)都已加载。
$(window).load(function(){
startDiv.find('img').each(function(p) {
$(this).parent().css({ height: thumbs_size, width:thumbs_size });
var height = $this.height(), width = $this.width();
var isPortrait = height > width;
$this.css({
height: isPortrait ? Math.ceil( height / width * thumbs_size) : thumbs_size,
width: isPortrait ? thumbs_size : Math.ceil(width / height * thumbs_size)
});
});
});你可能想给你的图片默认的宽度和高度与CSS
发布于 2012-07-18 08:08:52
更新:虽然上面的解决方案适用于任何独立的html页面,但Wordpress并不是以同样的方式处理所有事情,所以我对Wordpress使用了以下方法:
--将此javascript放入functions.php:https://github.com/alexanderdickson/waitForImages
--定义您的startDiv,例如: startDiv = $(".myThumbnailDiv");。
--在您的ready函数中,添加如下内容:
//Thumbnail parent container size, so they load within a thumbsize box
startDiv.find('img').each(function(p) {
$(this).parent().css({ height: thumbs_size, width:thumbs_size });
});
//Call the function in waitingforimages.js
startDiv.waitForImages(function() {
//alert('All images have loaded.');
}, function(loaded, count, success) {
var height = $(this).height(), width = $(this).width();
var isPortrait = height > width;
$(this).css({
height: isPortrait ? Math.ceil( height / width * thumbs_size) : thumbs_size,
width: isPortrait ? thumbs_size : Math.ceil(width / height * thumbs_size)
});
});https://stackoverflow.com/questions/11529011
复制相似问题