使图像居中而不是淡入淡出

时间:2013-11-15 22:41:58

标签: jquery css

这是我用来居中图像的CSS和jQuery的组合,但是我希望在它们居中之前隐藏图像,而不是以某种方式“淡化”它们。

CSS:

.image_block {
       position:relative;
       height:200px;
       width:200px;
 }

.img_block img {
    position: absolute;
    top:50%;
    left:50%;
    display:block;      
 }

jQuery的:

$('.img_block').find('img').each(function() {
  $(this).css({     
  'margin-left':  - $(this).outerWidth()/2,
  'margin-top':  - $(this).outerHeight()/2
  });
});

3 个答案:

答案 0 :(得分:1)

您可以使用以下方法隐藏CSS中的图像:

.img_block img { opacity: 0; }

然后使用jQuery .animate():

在相关图像上包含不透明度动画
$('.img_block').find('img').each(function() {
  $(this).css({     
    'margin-left':  - $(this).outerWidth()/2,
    'margin-top':  - $(this).outerHeight()/2
  });
  $(this).animate({     
    'opacity': 1
  });
});

答案 1 :(得分:0)

首先使用css隐藏您的图片:

.img_block img {
  position: absolute;
  top:50%;
  left:50%;
  // hide images
  display:none;      
}

然后在你的jQuery中,显示它们:

$('.img_block').find('img').each(function() {
  $(this).css({     
    'margin-left':  - $(this).outerWidth()/2,
    'margin-top':  - $(this).outerHeight()/2
  });
  // EDIT:
  $(this).show('slow');
  // OR
  $(this).fadeIn();
  // OR
  $(this).slideToggle('slow');
  // OR....
  setTimeout(function() {
    // show it here.
    $(this).show('slow');
  }, 1000);
});

答案 2 :(得分:0)

谢谢大家,我成功地完成了这项工作:

这是解决方案

CSS:

.img_block img {
  position: absolute;
  top:50%;
  left:50%;
  display:block;
  opacity:0;
  background-color: transparent;
  -webkit-transition: opacity 200ms linear;
  -moz-transition: opacity 200ms linear;
  -ms-transition: opacity 200ms linear;
  -o-transition: opacity 200ms linear;
  transition: opacity 200ms linear;         
}

jQuery的:

//center images 
function centerImages() {               
$('.img_block').find('img').each(function() {
  $(this).css({     
  'margin-left':  - $(this).outerWidth()/2,
  'margin-top':  - $(this).outerHeight()/2
  });
 });
}
//fadein images
function fadeImages(){
  $('.img_block').find('img').each(function() {
    $(this).delay(500).animate({'opacity': 1}, 0);
   });
  }
$.when(centerImages()).done(fadeImages);
相关问题