【问题标题】:center an image vertically using jquery使用jquery垂直居中图像
【发布时间】: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: 想一想,有一个缺点,那就是它在 所有 图像加载之前不会触发,当它们加载时这不是问题被缓存了,但是当它们没有被缓存时!也许您可以将这两种方法结合起来?
  • 你是对的,谢谢。实际上,相对而不是绝对解决了我的问题。

标签: jquery image center


【解决方案1】:

试试这个,我认为你正在失去图像的目标。

//Center the images (thumbnails) in the slideimg.js
function imageLoaded(thisImage) { // function to invoke for loaded image
  //get img dimensions
  var h = $(thisImage).height();
  //set img position
  $(thisImage).css('position','absolute');
  $(thisImage).css('top','50%');
  $(thisImage).css('margin-top',-Math.round(h/2) + 'px');
}
$(document).ready(function() {
 $('.work-view img').each(function(){
  if( this.complete ) {
    imageLoaded.call( this );
  } else {
    var self = this;
    $(this).one('load', function(){ imageLoaded(self); });
  }
 });
});

我所做的是将函数分解出来,并为其添加一个参数,因为您试图将this 多次传递给函数,但该函数不接受参数。在函数中,this 是指window

【讨论】:

  • 其实我把$(this).css('position','absolute');改成了$(this).css('position','relative');,现在可以了。我不知道为什么...
猜你喜欢
  • 1970-01-01
  • 2010-12-30
  • 1970-01-01
  • 2013-03-04
  • 2014-04-28
  • 2012-10-09
  • 2016-07-30
相关资源
最近更新 更多