且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用jQuery将完整大小的图像添加到网页的中心?

更新时间:2023-11-03 14:18:58

由于你想学习如何做到这一点,这里是一个相对简单的例子。代码位于下面,并发布到此粘贴程序

Since you want to learn how to do this, here is a relatively simple example. The code is below and also posted to this pastebin.

注意:脚本假定缩略图和全尺寸图像相同。如果图片 rel 属性不同,您可以将完整大小的图片网址存储在图片中。然后只需将popupImage src更改为: $(this).find('img')。attr('rel')

Note: The script assumes that the thumbnail and full-sized image are the same. You can store the full size image URL in the image rel attribute if it is different. Then just change the popupImage src to this: $(this).find('img').attr('rel')

CSS

#overlay {
 position: absolute;
 left: 0;
 top: 0;
 height: 100%;
 width: 100%;
 background: #000;
 opacity: 0.8;
 filter: alpha(opacity=80);
}
#popupImage {
 position: absolute;
 left: -99999px;
 top: 0;
}

HTML示例

<a class="cell"><img src="http://i47.tinypic.com/2m2c36v.jpg" width="30" /></a>

脚本

$(document).ready(function(){
 $('a.cell').click(function(){

  // Add overlay
  $('<div id="overlay" />')
   .hide()
   .appendTo('body')
   .fadeIn('slow');

  // Add image & center
  $('<img id="popupImage" src="' + $(this).find('img').attr('src') + '">').appendTo('body');
  var img = $('#popupImage');
  var imgTop = ($(window).height() - img.height())/2;
  var imgLft = ($(window).width() - img.width())/2;
  img
   .hide()
   .css({ top: imgTop, left: imgLft })
   .fadeIn('slow');

  // Add click functionality to hide everything
  $('#overlay,#popupImage').click(function(){
   $('#overlay,#popupImage').fadeOut('slow',function(){
     $(this).remove();
     $('#overlay').remove();
   });
  })
 });
})