【发布时间】:2012-10-06 23:18:06
【问题描述】:
为了使图像垂直居中(this page 上的缩略图),我尝试了这个:
//Center the images (thumbnails) in the slideimg.js
$(document).ready(function() {
$('.work-view img').load(function(){
//get img dimensions
var h = $(this).height();
//alert(h);
//set img position
$(this).css('position','absolute');
$(this).css('top','50%');
$(this).css('margin-top',-Math.round(h/2) + 'px');
});
});
但它适用于 Chrome,但不适用于 firefox,因为 firefox 将图像放在缓存中,而 .load 仅用于加载图像。 所以我正在尝试这个:
//Center the images (thumbnails) in the slideimg.js
$(document).ready(function() {
function imageLoaded() { // function to invoke for loaded image
//get img dimensions
var h = $(this).height();
//alert(h);
//set img position
$(this).css('position','absolute');
$(this).css('top','50%');
$(this).css('margin-top',-Math.round(h/2) + 'px');
}
$('.work-view img').each(function(){
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
});
但它不起作用...$(this).css('position','absolute'); 将它们向右移动,而不是让它们水平放置...我做错了什么吗?
【问题讨论】:
-
不,它们也应该水平居中到直接的 html 父级中……但奇怪的是它们向右太多了。
$(this).css('position','absolute');将它们向右移动... -
你不能向窗口添加负载处理程序而不是单个图像吗?这应该可以解决您的缓存不触发加载事件的问题。
-
@MattBurland 你的意思是window.load,不是有缺点吗?
-
@louis: 想一想,有一个缺点,那就是它在 所有 图像加载之前不会触发,当它们加载时这不是问题被缓存了,但是当它们没有被缓存时!也许您可以将这两种方法结合起来?
-
你是对的,谢谢。实际上,相对而不是绝对解决了我的问题。