欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jquery插件制作 图片走廊 gallery

程序员文章站 2022-07-24 13:58:39
首先创建jquery.gallery.js的插件文件,构建程序骨架。 代码如下: (function ($) {   $.fn.gallery = function ()...

首先创建jquery.gallery.js的插件文件,构建程序骨架。

代码如下:


(function ($) {
  $.fn.gallery = function () {
    return this.each(function () {
      var self = $(this);
      self.click(function () {

      });
    });
  }
})(jQuery);


  创建html文件,使用我们创建的插件。

. 代码如下:


<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="Scripts/jquery-1.6.2.js"></script>
<script type="text/javascript" src="Scripts/jquery.gallery.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('img').gallery();
});
</script>
</head>
<body>
<img src="Images/orderedList1.png" alt="" />
<img src="Images/orderedList2.png" alt="" />
<img src="Images/orderedList3.png" alt="" />
</body>
</html>  


现在我们开始考虑如何实现点击图片的时候,显示放大图片的效果。其实我们显示放大的图片不是原先的图片,而是我们clone出了一个新图片,将他添加到页面中并加以显示。此外通过计算页面高度、宽度,图片高度、宽度,滚动条位置,来实现大图居中对齐的实现。下面我们看改进后的代码:

. 代码如下:


(function ($) {
$.fn.gallery = function () {
return this.each(function () {
//将this变量保存到self,目的是为了避免程序错误
//至于原因,上章简单提到this在函数上下中中代表的对象不同
var self = $(this);
//统一将小图的高度设置成100(根据个人需要可以调整,或者提供options选项)
self.height(100);

//添加click事件
self.click(function () {
//移除id为myImgGallery的对象,其实这个对象就是大图对象
//每次点击的时候,都要移除上一次点击时产生的大图
$('#myImgGallery').remove();

self.clone() //jquery的clone方法,clone图片
.attr('id', 'myImgGallery')//设置id为myImgGallery
.height($(window).height() / 2)//将图片高度设置为页面可用区域高度的一半(根据自己的需要也可以设置成其他值)
.css({
position: 'absolute'
})
.prependTo('body')//将大图添加到body对象中
//使用自己创建的center插件,实现图片居中
//注意,一定要将clone的对象添加到body后才能调用center方法,否则clone对象的width和height都为0
.center()
.click(function () {//添加大图的click事件
$(this).remove(); //点击大图时,删除本身
});
});
});
};
$.fn.center = function () {
return this.each(function () {
$(this).css({
//设置绝对定位,这样他就会浮动在最上层(必要的情况下可以设置zindex属性)
position: 'absolute',
//设置垂直居中对齐
top: ($(window).height() - $(this).height()) / 2 + $(window).scrollTop() + 'px',
//设置水平居中对齐
left: ($(window).width() - $(this).width()) / 2 + $(window).scrollLeft() + 'px'
});
});
};
})(jQuery);