Красивые странички: решение с помощью jQuery

Сегодня мы с вами сделаем JQuery плагин, который позволит конвертировать обычный неупорядоченный список элементов в SEO-дружественный набор легко переключаемых страниц. Он может быть использован для организации комментариев, слайд-шоу или какой-либо другой структурированной информации.

Шаг 1: XHTML

Первым шагом нашего урока является создание разметки XHTML. Кароч, для плагина всего-то что и нужну это - неупорядочненный список, Ul, с несколькими Li-шками внутри них. Ниже представлен код)
    <div id="main">
        <ul id="holder">
            <li>Lorem ipsum dolor sit amet...</li>
            <li>Lorem ipsum dolor sit amet...</li>
            <li>Lorem ipsum dolor sit amet...</li>
            <li>Lorem ipsum dolor sit amet...</li>
        </ul>
    </div>

Наш главный div выступает в роли контейнера для Ul-ки, исполненный в красивом светло-сером стиле. Высота и размер динамически расчитываются с помощью JQuery, но если вы собираетесь использовать изображения - необходимо будет указать ширину и высоту (помните!).

Красивые странички: решение с помощью jQuery

Шаг 2: CSS

После создания XHTML разметки, мы можем приступать к созданию стилей. Чем сейчас и займемся.

Styles.css - часть 1
    #main{
        /* The main container div */
        position:relative;
        margin:50px auto;
        width:410px;
        background:url('img/main_bg.jpg') repeat-x #aeadad;
        border:1px solid #CCCCCC;
        padding:70px 25px 60px;
     
        /* CSS3 rounded cornenrs */
     
        -moz-border-radius:12px;
        -webkit-border-radius:12px;
        border-radius:12px;
    }
     
    #holder{
        /* The unordered list that is to be split into pages */
     
        width:400px;
        overflow:hidden;
        position:relative;
        background:url('img/dark_bg.jpg') repeat #4e5355;
        padding-bottom:10px;
     
        /*  CSS3 inner shadow (the webkit one is commeted, because Google Chrome
            does not like rounded corners combined with inset shadows): */
     
        -moz-box-shadow:0 0 10px #222 inset;
        /*-webkit-box-shadow:0 0 10px #222 inset;*/
        box-shadow:0 0 10px #222 inset;
    }
     
    .swControls{
        position:absolute;
        margin-top:10px;
    }

Обратите внимание на то, как мы используем "box shadow" в CSS3, что-бы имитировать внутреннюю тень. Также в соответствии со всеми правилами CSS3 мы должны "позаботиться" о конкретных браузерах, таких как Mozila, Safari и Chrome.

Styles.css - часть 2
    a.swShowPage{
     
        /* The links that initiate the page slide */
     
        background-color:#444444;
        float:left;
        height:15px;
        margin:4px 3px;
        text-indent:-9999px;
        width:15px;
        /*border:1px solid #ccc;*/
     
        /* CSS3 rounded corners */
     
        -moz-border-radius:7px;
        -webkit-border-radius:7px;
        border-radius:7px;
    }
     
    a.swShowPage:hover,
    a.swShowPage.active{
        background-color:#2993dd;
     
        /*  CSS3 inner shadow */
     
        -moz-box-shadow:0 0 7px #1e435d inset;
        /*-webkit-box-shadow:0 0 7px #1e435d inset;*/
        box-shadow:0 0 7px #1e435d inset;
    }
     
    #holder li{
        background-color:#F4F4F4;
        list-style:none outside none;
        margin:10px 10px 0;
        padding:20px;
        float:left;
     
        /* Regular CSS3 box shadows (not inset): */
     
        -moz-box-shadow:0 0 6px #111111;
        -webkit-box-shadow:0 0 6px #111111;
        box-shadow:0 0 6px #111111;
    }
     
    #holder,
    #holder li{
        /* Applying rouded corners to both the holder and the holder lis */
        -moz-border-radius:8px;
        -webkit-border-radius:8px;
        border-radius:8px;
    }
     
    .clear{
        /* This class clears the floated elements */
        clear:both;
    }

Во второй части кода мы с вами написали стили для преключения страниц и Li-шек. Как вы могли заметить, в 46-й строке мы закругляем углы маркированного списка и li элементов, что спасает нас от дублирования кода.

Шаг 3: jQuery

Переходя к последней части урока, мы должны добавить на страницу самую последнюю версию библиотеки jQuery. Лучше всего инклудить внешние файлы javascript перед зкрытием тега "body".

script.js - часть 1
    (function($){
     
    // Creating the sweetPages jQuery plugin:
    $.fn.sweetPages = function(opts){
     
        // If no options were passed, create an empty opts object
        if(!opts) opts = {};
     
        var resultsPerPage = opts.perPage || 3;
     
        // The plugin works best for unordered lists,
        // although OLs would do just as well:
        var ul = this;
        var li = ul.find('li');
     
        li.each(function(){
            // Calculating the height of each li element,
            // and storing it with the data method:
     
            var el = $(this);
            el.data('height',el.outerHeight(true));
       });
     
        // Calculating the total number of pages:
        var pagesNumber = Math.ceil(li.length/resultsPerPage);
     
        // If the pages are less than two, do nothing:
        if(pagesNumber<2) return this;
     
        // Creating the controls div:
        var swControls = $('<div class="swControls">');
     
        for(var i=0;i<pagesNumber;i++)
        {
            // Slice a portion of the li elements, and wrap it in a swPage div:
            li.slice(i*resultsPerPage,(i+1)*resultsPerPage).wrapAll('<div class="swPage" />');
     
            // Adding a link to the swControls div:
            swControls.append('<a href="" class="swShowPage">'+(i+1)+'</a>');
        }
     
        ul.append(swControls);

script.js - часть 2
        var maxHeight = 0;
        var totalWidth = 0;
     
        var swPage = ul.find('.swPage');
        swPage.each(function(){
     
            // Looping through all the newly created pages:
     
            var elem = $(this);
     
            var tmpHeight = 0;
            elem.find('li').each(function(){tmpHeight+=$(this).data('height');});
     
            if(tmpHeight>maxHeight)
                maxHeight = tmpHeight;
     
            totalWidth+=elem.outerWidth();
     
            elem.css('float','left').width(ul.width());
        });
     
        swPage.wrapAll('<div class="swSlider" />');
     
        // Setting the height of the ul to the height of the tallest page:
        ul.height(maxHeight);
     
        var swSlider = ul.find('.swSlider');
        swSlider.append('<div class="clear" />').width(totalWidth);
     
        var hyperLinks = ul.find('a.swShowPage');
     
        hyperLinks.click(function(e){
     
            // If one of the control links is clicked, slide the swSlider div
            // (which contains all the pages) and mark it as active:
     
            $(this).addClass('active').siblings().removeClass('active');
     
            swSlider.stop().animate({'margin-left': -(parseInt($(this).text())-1)*ul.width()},'slow');
            e.preventDefault();
        });
     
        // Mark the first link as active the first time the code runs:
        hyperLinks.eq(0).addClass('active');
     
        // Center the control div:
        swControls.css({
            'left':'50%',
            'margin-left':-swControls.width()/2
        });
     
        return this;
     
    }})(jQuery);

script.js – часть 3
    $(document).ready(function(){
        /* The following code is executed once the DOM is loaded */
     
        // Calling the jQuery plugin and splitting the
        // #holder UL into pages of 3 LIs each:
     
        $('#holder').sweetPages({perPage:3});
     
        // The default behaviour of the plugin is to insert the
        // page links in the ul, but we need them in the main container:
     
        var controls = $('.swControls').detach();
        controls.appendTo('#main');
     
    });

Заключение

С помощью этого плагина вы сможете организовать любые виды комментариев, слайд-шоу, страницы с описанием товара или другие виды данных. Преимущество заключается в том, что даже при "отключенном" javascript'е в итоге получается семантический, SEO дружественных код. Удачи)
Теги:
Красивые странички
Добавлено: 20 Мая 2018 06:48:03 Добавил: Андрей Ковальчук Нравится 0
Добавить
Комментарии:
Нету комментариев для вывода...