jquery插件制作 -- 2.圖片走廊:gallery


  本文主要內容是講解圖片走廊-gallery的實現。

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

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

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

  創建html文件,使用我們創建的插件。

<!DOCTYPE html>
<html xmlns="http://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);

 

  好了,今天的內容到此結束。

demo下載地址:jQuery.plugin.gallery.zip


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM