Разбитие содержания стандартный выбор при работе с большими кусками данных. Осуществляется это обычно след. образом: включает в себя номер страницы, где соответствующие данные извлекаются из базы данных и возвращается в той или иной форме. Трудоемкий процесс, но это необходимое зло.
При работе с небольшими наборами данных, было бы лучше иметь содержание легко доступным, но по-прежнему аккуратно организованным.
Сегодня мы делаем JQuery плагин, который позволит вам конвертировать неупорядоченный список элементов. Он может быть использован для комментариев темы, слайд-шоу, или каких-либо других элементов структурированного контента.
Идея
При вызове, JQuery плагин распознает LI элементы и группирует их по 3 штуки.
Разбитие новостей на страниции (JQuery)
Шаг 1 - XHTML
Первым шагом урока является создание разметки XHTML. Плагину нужно только неупорядоченный список, UL, с некоторыми элементами Li внутри него. Вот код из demo.html, который вы можете найти в архиве:
<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>
Плагин будет преобразовывать наш контент в нечто подобное:
Шаг 2 - CSS
После создания разметки XHTML, мы можем перейти к моделированию его. CSS стили будут связаны с javascript. Это означает, что если у пользователей будут отключены js то они не смогут увидеть и использовать нумерацию. Хотя сейчас таких пользователей почти не осталось.
styles.css
#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;
}
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;
}
Шаг 3 - JQuery
Переход к последней части урока, мы должны подключить последнюю версию библиотеки JQuery в страницу. С точки зрения производительности, лучше включать в себя все внешние файлы javascript, как раз перед закрытием тега тела.
script.js
(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);
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);
$(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');
});
Наше сладкое решение нумерации страниц с JQuery и CSS3 успешно закончено!