JavaScript >> Javascript 文檔 >  >> jQuery

不斷增長的縮略圖組合

在本教程中,我們將使用 HTML5、jQuery 和 CSS3 製作一個具有有趣成長效果的作品集。

HTML

像往常一樣,我們從一個空白的 HTML5 文檔開始,然後添加所需的樣式表、標記和 JavaScript 包含。

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>Growing Thumbnails Portfolio with jQuery &amp; CSS3 | Tutorialzine Demo</title>

        <!-- The stylesheet -->
        <link rel="stylesheet" href="assets/css/styles.css" />

        <!-- Google Fonts -->
        <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Rochester|Bree+Serif" />

        <!--[if lt IE 9]>
          <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
    </head>

    <body>

        <header>
            <h2>Welcome to</h2>
            <h1>Dan's Portfolio</h1>
        </header>

        <div id="main">

            <h3>My Latest Projects</h3>

            <a class="arrow prev">Prev</a>
            <a class="arrow next">Next</a>

            <ul id="carousel">
                <li class="visible"><a href=""><img src="assets/img/sites/s1.jpg" alt="" /></a></li>
            <!--  Place additional items here -->
            </ul>

        </div>

        <!-- JavaScript includes - jQuery and our own script.js -->
        <script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
        <script src="assets/js/script.js"></script>

    </body>
</html>

這裡要注意的重要一點是 #carousel 無序列表。此元素包含代表您最近作品的 li 項目的集合。僅當要顯示縮略圖時才添加可見類。一次只能看到三個縮略圖。超鏈接的 href 屬性可以指向相關網站,或者如果您打算在本示例中使用燈箱,則可以指向更大版本的圖像。

JavaScript

此示例的所有 JavaScript/jQuery 代碼都位於 assets/js/script.js 中 .我們將編寫一個名為 Navigator 的 JavaScript 類 這將為我們管理輪播。這將涉及編寫監聽箭頭點擊的方法,將輪播分成 3 個項目的組並顯示它們。

以下是該類的使用方式:

$(document).ready(function(){

    // Initialize the object on dom load
    var navigator = new Navigator({
        carousel: '#carousel',
        nextButton: '.arrow.next',
        prevButton: '.arrow.prev',
        // chunkSize:3,
        shuffle: true
    });

    navigator.init();
});

加載文檔時,我們將創建一個類的實例,傳遞輪播 div、箭頭和一個可選參數,以決定是否要對列表進行打亂。這裡還有一個參數 - chunkSize .此屬性決定一次顯示多少個縮略圖,默認為 3 個。

實現這一點的第一步,是編寫類的佈局:

// A Navigator "class" responsible for navigating through the carousel.
function Navigator(config) {

    this.carousel = $(config.carousel); //the carousel element
    this.nextButton = $(config.nextButton); //the next button element
    this.prevButton = $(config.prevButton); //the previous button element
    this.chunkSize = config.chunkSize || 3; //how many items to show at a time (maximum)
    this.shuffle = config.shuffle || false; //should the list be shuffled first? Default is false.

    //private variables
    this._items = $(config.carousel + ' li'); //all the items in the carousel
    this._chunks = []; //the li elements will be split into chunks.
    this._visibleChunkIndex = 0; //identifies the index from the this._chunks array that is currently being shown

    this.init = function () {

        // This will initialize the class, bind event handlers,
        // shuffle the li items, split the #carousel list into chunks

    }

    // Method for handling arrow clicks
    this.handlePrevClick = function(e) {};
    this.handleNextClick = function(e) {};

    // show the next chunk of 3 lis
    this.showNextItems = function() {};

    // show the previous chunk of 3 lis
    this.showPrevItems = function() {};

    // These methods will determine whether to
    // show or hide the arrows (marked as private)
    this._checkForBeginning = function() {};
    this._checkForEnd = function() {};

    // A helper function for splitting the li
    // items into groups of 3
    this._splitItems = function(items, chunk) {};
}

我們使用下劃線來表示哪些屬性和方法是私有的。外部代碼不應使用以下劃線開頭的任何屬性。

在下面的片段中,您可以看到每個方法是如何實現的。首先是 init(),它通過綁定事件監聽器和對輪播 ul 進行分區來設置輪播。

this.init = function () {

    //Shuffle the array if neccessary
    if (this.shuffle) {
        //remove visible tags
        this._items.removeClass('visible');

        //shuffle list
        this._items.sort(function() { return 0.5 - Math.random() });

        //add visible class to first "chunkSize" items
        this._items.slice(0, this.chunkSize).addClass('visible');
    }

    //split array of items into chunks
    this._chunks = this._splitItems(this._items, this.chunkSize);

    var self = this;

    //Set up the event handlers for previous and next button click
    self.nextButton.on('click', function(e) {
        self.handleNextClick(e);
    }).show();

    self.prevButton.on('click', function(e) {
        self.handlePrevClick(e);
    });

    // Showing the carousel on load
    self.carousel.addClass('active');
};

接下來是處理箭頭點擊的方法。

this.handlePrevClick = function (e) {

    e.preventDefault();

    //as long as there are some items before the current visible ones, show the previous ones
    if (this._chunks[this._visibleChunkIndex - 1] !== undefined) {
        this.showPrevItems();
    }
};

this.handleNextClick = function(e) {

    e.preventDefault();

    //as long as there are some items after the current visible ones, show the next ones
    if (this._chunks[this._visibleChunkIndex + 1] !== undefined) {
        this.showNextItems();
    }
};

他們恭敬地調用 showPrevItems 和 showNextItems:

this.showNextItems = function() {

    //remove visible class from current visible chunk
    $(this._chunks[this._visibleChunkIndex]).removeClass('visible');

    //add visible class to the next chunk
    $(this._chunks[this._visibleChunkIndex + 1]).addClass('visible');

    //update the current visible chunk
    this._visibleChunkIndex++;

    //see if the end of the list has been reached.
    this._checkForEnd();

};

this.showPrevItems = function() {

    //remove visible class from current visible chunk
    $(this._chunks[this._visibleChunkIndex]).removeClass('visible');

    //add visible class to the previous chunk
    $(this._chunks[this._visibleChunkIndex - 1]).addClass('visible');

    //update the current visible chunk
    this._visibleChunkIndex--;

    //see if the beginning of the carousel has been reached.
    this._checkForBeginning();

};

上述方法刪除或分配 可見 類,這是我們控制縮略圖可見性的方式。如果沒有其他要顯示的項目,最好隱藏上一個/下一個箭頭。這是通過 checkForBeginning 完成的 和 checkForEnd 方法。

this._checkForBeginning = function() {
    this.nextButton.show(); //the prev button was clicked, so the next button can show.

    if (this._chunks[this._visibleChunkIndex - 1] === undefined) {
        this.prevButton.hide();
    }
    else {
        this.prevButton.show();
    }
};

this._checkForEnd = function() {
    this.prevButton.show(); //the next button was clicked, so the previous button can show.

    if (this._chunks[this._visibleChunkIndex + 1] === undefined) {
        this.nextButton.hide();
    }
    else {
        this.nextButton.show();
    }
};

最後,這裡是 splitItems 方法,它生成塊。它依賴於 splice JavaScript 方法來移除部分數組並將它們添加到 splitItems 數組中(它變成了數組的數組):

this._splitItems = function(items, chunk) {

    var splitItems = [],
    i = 0;

    while (items.length > 0) {
        splitItems[i] = items.splice(0, chunk);
        i++;
    }

    return splitItems;

};

恭喜!您現在有一個工作示例。我們只剩下樣式了。

CSS

投資組合的樣式在 assets/css/styles.css 中定義。這裡只展示比較有趣的部分,為簡潔起見省略了其餘部分。

#carousel{
    margin-top:200px;
    text-align:center;
    height:60px;
    background-color:#111;
    box-shadow:0 3px 5px #111;

    /* Initially hidden */
    opacity:0;

    /* Will animate the grow effect */
    -moz-transition:0.4s opacity;
    -webkit-transition:0.4s opacity;
    transition:0.4s opacity;
}

#carousel.active{
    opacity:1;
}

/* The thumbnails, hidden by default */

#carousel li{
    display:none;
    list-style:none;
    width:150px;
    height:150px;
    margin: -82px 18px 0;
    position:relative;

    -moz-transition:0.4s all;
    -webkit-transition:0.4s all;
    transition:0.4s all;
}

/* This class will show the respective thumbnail */

#carousel li.visible{
    display:inline-block;
}

#carousel li a img{
    border:none;
}

#carousel li img{
    display:block;
    width:auto;
    height:auto;
    max-width:100%;
    max-height:100%;
    position:relative;
    z-index:10;
}

/* Creating the cradle below the thumbnails.
    Uses % so that it grows with the image. */

#carousel li:after{
    content:'';
    background:url('../img/cradle.png') no-repeat top center;
    background-size:contain;
    bottom: 4%;
    content: "";
    height: 50px;
    left: -6.5%;
    position: absolute;
    right: -6.5%;
    width: auto;
    z-index: 1;
}

/* Enlarging the thumbnail */

#carousel li:hover{
    height: 197px;
    margin-top: -152px;
    width: 222px;
}

有了這個,我們的成長縮略圖組合就完成了!

這是一個包裝!

您可以通過合併一個燈箱腳本、增加一次顯示的縮略圖數量,甚至將它變成一個畫廊來輕鬆自定義今天的示例。如果您做了一些有趣的事情,請務必在下面的評論部分分享!


Tutorial JavaScript 教程
  1. 這個免費工具可讓您為 React 組件創建世界一流的文檔

  2. MERN-如何動態添加行並將其存儲在 mongodb

  3. 從 if/switch 到映射函數(又名對象查找)

  4. 使用 Node.js 跟踪 URL 重定向

  5. 使用 Wails 在 Go 中構建桌面應用程序

  6. 如何將 JavaScript 與 Selenium WebDriver Java 一起使用

  7. 我的牛肉🥩 使用 Javascript 和 ReactJS ⚛️

  1. 使用 Node.js fs 模塊獲取文件信息

  2. React:將 HTML 元素渲染到 DOM

  3. 🌍簡單的數字時鐘 (JS) [YouTube LIVE]

  4. 🔥 Vue 技巧 #30:可重用性基礎:配置模式

  5. 我是如何製作我的第一個全棧 Web 應用程序的? 🚀

  6. 用 JavaScript 理解 Big-O 表示法

  7. 在 JavaScript 中對對像數組進行排序的 3 個巧妙技巧

  1. 解釋(和慶祝)我的第一個 Twitter Bot

  2. Angular 14 中帶有動態導入的延遲加載模塊

  3. 在 ASP.NET Core 中模擬延遲

  4. ANKO - 一位父親試圖讓女兒愛上數學