JQuery Шаблоны – практичное использование

Сегодня мы поговорим о JQuery. JQuery шаблоны могут помочь вам с форматированием данных, получаемых с вызова Ajax (как пример). Или, мы можем использовать уже предопределенные данные. Наш пример будет состоять из 2 частей. Сначала один преобразит данные как набор фотографий. Второй — как набор статей. Кроме того, сегодня мы рассмотрим (в нашем примере), как изменить шаблоны при нажатии мыши.
Демо
Исходники

Шаг 1. HTML

Вот полный HTML-код галереи. Здесь вы можете увидеть два основные объекта DIV с ID  галерей и статьями. Первый будет преобразован в галерею, второй — в список статей.

index.html

<!DOCTYPE html>
<html lang="en" >
    <head>
        <meta charset="utf-8" />
        <title>jQuery Templates | Script Tutorials</title>
        <link href="css/main.css" rel="stylesheet" type="text/css" />

        <!--[if lt IE 9]>
          <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
        <![endif]-->
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
        <script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
        <script type="text/javascript" src="js/script.js"></script>
    </head>
    <body>
        <div class="container" id="container">
            <h2>Photo gallery example</h2>
            <div class="gallery" id="gallery"></div>
            <hr />
            <h2>Articles</h2>
            <div class="articles" id="articles"></div>
        </div>
        <footer>
            <h2>jQuery Templates (article)</h2>
            <a href="http://www.script-tutorials.com/jquery-templates-practice-of-using/" class="stuts">Back to original tutorial on <span>Script Tutorials</span></a>
        </footer>
    </body>
</html>

Шаг 2. CSS

css/main.css

/* page layout */
*{
    margin:0;
    padding:0;
}
body {
    background-color:#bababa;
    color:#fff;
    font:14px/1.3 Arial,sans-serif;
}
footer {
    background-color:#212121;
    bottom:0;
    box-shadow: 0 -1px 2px #111111;
    -moz-box-shadow: 0 -1px 2px #111111;
    -webkit-box-shadow: 0 -1px 2px #111111;
    display:block;
    height:70px;
    left:0;
    position:fixed;
    width:100%;
    z-index:100;
}
footer h2{
    font-size:22px;
    font-weight:normal;
    left:50%;
    margin-left:-400px;
    padding:22px 0;
    position:absolute;
    width:540px;
}
footer a.stuts,a.stuts:visited{
    border:none;
    text-decoration:none;
    color:#fcfcfc;
    font-size:14px;
    left:50%;
    line-height:31px;
    margin:23px 0 0 110px;
    position:absolute;
    top:0;
}
footer .stuts span {
    font-size:22px;
    font-weight:bold;
    margin-left:5px;
}
.container {
    background:#ddd;
    color:#000;
    margin:20px auto 100px;
    padding:20px;
    position:relative;
    width:700px;

    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;

    box-shadow:1px 1px 5px #111;
    -moz-box-shadow:1px 1px 5px #111;
    -webkit-box-shadow:1px 1px 5px #111;
}
.container h2 {
    margin-bottom:20px;
    text-align:center;
}

/* css3 photo gallery styles */
.gallery {
    width:610px;
    margin:10px auto;
    position:relative;
}
.gallery a {
    display:block;
    height:100px;
    position:relative;
    width:133px;
}
.gallery a img {
    border:5px solid #fff;
    cursor:pointer;
    display:block;
    height:100%;
    left:0px;
    position:absolute;
    top:0px;
    width:100%;
    z-index:1;

    -moz-user-select: none;
    -khtml-user-select: none;
    user-select: none;

    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    box-sizing:border-box;

    -webkit-transition-property:width, height, top, bottom, left, right, z-index, border;
    -webkit-transition-duration:0.5s;
    -moz-transition-property:width, height, top, bottom, left, right, z-index, border;
    -moz-transition-duration:0.5s;
    -o-transition-property:width, height, top, bottom, left, right, z-index, border;
    -o-transition-duration:0.5s;
    transition-property:width, height, top, bottom, left, right, z-index, border;
    transition-duration:0.5s;
}
.gallery a:focus img {
    border:15px solid #fff;
    cursor:default;
    height:250%;
    position:absolute;
    width:250%;
    z-index:25;
    top:0px;
    right:0px;

    box-shadow:1px 1px 5px #888;
    -moz-box-shadow:1px 1px 5px #888;
    -webkit-box-shadow:1px 1px 5px #888;
    -webkit-transition-property:width, height, top, bottom, left, right, z-index, border;
    -webkit-transition-duration:0.5s;
    -moz-transition-property:width, height, top, bottom, left, right, z-index, border;
    -moz-transition-duration:0.5s;
    -o-transition-property:width, height, top, bottom, left, right, z-index, border;
    -o-transition-duration:0.5s;
    transition-property:width, height, top, bottom, left, right, z-index, border;
    transition-duration:0.5s;
}

/* custom focus rules */
.gallery a:focus:nth-child(1) img {
    top:0px;
}
.gallery a:focus:nth-child(2) img {
    top:-100px;
}
.gallery a:focus:nth-child(3) img {
    top:-200px;
}
.gallery a:focus:nth-child(4) img {
    top:-300px;
}

/* extra close layer */
.gallery .close {
    background:transparent;
    cursor:pointer;
    display:none;
    height:270px;
    left:0px;
    position:absolute;
    top:0px;
    width:300px;
    z-index:30;
}
.gallery a:focus ~ .close {
    display:block;
}

/* articles */
.articles {
    overflow:hidden;
}
.articles > div {
    border:1px solid #444;
    float:left;
    margin:0 1% 10px;
    width:48%;

    border-radius:5px;
    -moz-border-radius:5px;
    -webkit-border-radius:5px;

    box-shadow: 0 1px 2px #111111;
    -moz-box-shadow: 0 1px 2px #111111;
    -webkit-box-shadow: 0 1px 2px #111111;

    -moz-box-sizing:border-box;
    -webkit-box-sizing:border-box;
    box-sizing:border-box;
}
.articles div img {
    cursor:pointer;
    float:left;
    margin-right:20px;
    width:128px;
}
.articles div div {
    float:left;
    margin-top:8px;
    width:128px;
}
.articles div div p:nth-child(1) {
    color:#444;
    font-size:12px;
}
.articles div div p:nth-child(2) {
    font-size:17px;
    font-weight:bold;
}
.articles div.sim div p:nth-child(2) {
    cursor:pointer;
}
Step 3. jQuer

Шаг 3. jQuery

Сейчас время понять наш JS код (и как работать с JQuery шаблонами).

js/script.js

var photos = [
  { Image: '1.jpg', Date: '27 Oct 2011', About: 'This is description about 1.jpg' },
  { Image: '2.jpg', Date: '28 Oct 2011', About: 'This is description about 2.jpg' },
  { Image: '3.jpg', Date: '29 Oct 2011', About: 'This is description about 3.jpg' },
  { Image: '4.jpg', Date: '30 Oct 2011', About: 'This is description about 4.jpg' }
];

$(function(){
    // prepare own custom templates
    $.template('simplePhotos', '<a tabindex="1"><img src="images/${Image}"></a>');

    $.template('simpleArticles', '<div class="sim"><img src="images/${Image}"><div><p></p><p>more details</p></div></div>');
    $.template('extendedArticles', '<div class="ext"><img src="images/${Image}"><div><p>${Date}</p><p>${About}</p></div></div>');

    var selectedItem = null;

    // render Photos and Articles through prepared templates
    $.tmpl('simplePhotos', photos).appendTo('#gallery');
    $('<span class="close"></span>').appendTo('#gallery');

    $.tmpl('simpleArticles', photos ).appendTo('#articles');

    // onclick handling
    $('#articles').delegate('.sim', 'click', function () {
      if (selectedItem) {
        // render via Simple template
        selectedItem.tmpl = $.template('simpleArticles');
        selectedItem.update();
      }

      selectedItem = $.tmplItem(this);

      // render via Extended template
      selectedItem.tmpl = $.template('extendedArticles');
      selectedItem.update();
    }).delegate( '.ext', 'click', function () {
      // render via Simple template
      selectedItem.tmpl = $.template('simpleArticles');
      selectedItem.update();

      selectedItem = null;
    });
});

Сначала, опредим массив данных, которые мы собираемся использовать:

var photos = [
  { Image: '1.jpg', Date: '27 Oct 2011', About: 'This is description about 1.jpg' },
  { Image: '2.jpg', Date: '28 Oct 2011', About: 'This is description about 2.jpg' },
  { Image: '3.jpg', Date: '29 Oct 2011', About: 'This is description about 3.jpg' },
  { Image: '4.jpg', Date: '30 Oct 2011', About: 'This is description about 4.jpg' }
];

Это обычный массив с нашими собственными полями. Затем определим три различных шаблона JQuery (для обеих целей):

$.template('simplePhotos', '<a tabindex="1"><img src="images/${Image}"></a>');

    $.template('simpleArticles', '<div class="sim"><img src="images/${Image}"><div><p></p><p>more details</p></div></div>');
    $.template('extendedArticles', '<div class="ext"><img src="images/${Image}"><div><p>${Date}</p><p>${About}</p></div></div>');

И только после этого применим наши готовые шаблоны с помощью «TMPL» функции:

$.tmpl('simplePhotos', photos).appendTo('#gallery');

    $.tmpl('simpleArticles', photos ).appendTo('#articles');

Последний код используется для моментального переключения шаблонов (в случае нажатия на статьи):

 selectedItem.tmpl = $.template('extendedArticles');
      selectedItem.update();

Я надеюсь, что урок вышел легким. Хотите создать сайт на ASP.NET тогда вам сюда создание сайтов на ASP.NET (AJAX)

Категория: JQuery, Новости Теги: 

Популярные записи:

Шаблон Flash – Content Grid    Шаблон Flash – Content Grid   
Шаблон Flash – 3D Touch Ring Шаблон Flash – 3D Touch Ring
Модульная сетка в современном веб-дизайне Модульная сетка в современном веб-дизайне
Шаблон Flash — Black PAD Шаблон Flash — Black PAD

Оставить комментарий или два

Отправить коментарий

Test

Яндекс.Метрика