Приветствую вас дорогие читатели, сегодня я хотел бы отвлечься от Kohana и рассказать вам о том как можно сделать красивое, красочное и анимированное меню на jQuery. Интересно?
1. Создание html разметки
Листинг файла index.html:
<!DOCTYPE html> <html> <head> <title>Красочное анимированное jQuery меню</title> <link rel="stylesheet" type="text/css" media="all" href="assets/screen.css" /> <script type="text/javascript" src="//yandex.st/jquery/1.7.2/jquery.min.js"></script> <script type="text/javascript" src="//yandex.st/jquery/easing/1.3/jquery.easing.min.js"></script> <script type="text/javascript" src="assets/menu.js"></script> </head> <body> <!-- start wrapper --> <div id="wrapper"> <!-- start menu --> <div id="menu"> <span class="colourful"></span> <ul> <li><a href="#web-design">Web Design</a></li> <li><a class="current" href="#jquery">jQuery</a></li> <li><a href="#html5css3">Html5 & Css3</a></li> <li><a href="#php">PHP</a></li> <li><a href="#photoshop">Photoshop</a></li> <li><a href="#illustrator">Illustrator</a></li> <li><a href="#wordpress">Wordpress</a></li> <li><a href="#tutorials">Tutorials</a></li> <li><a href="#tutorialpot">tutorialpot</a></li> </ul> </div> <!-- end menu --> </div> <!-- end wrapper --> <div class="clr"></div> </body> </html>
2 Создание таблицы стилей
Листинг файла assets/screen.css:
/* Eric Meyer css reset */
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, font, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td { margin: 0; padding: 0; border: 0; outline: 0; font-size: 100%; vertical-align: baseline; background: transparent; }
body { line-height: 21px; }
blockquote, q { quotes: none; }
blockquote:before, blockquote:after, q:before, q:after { content: ''; content: none; }
/* remember to define focus styles! */
:focus { outline: 0; }
/* remember to highlight inserts somehow! */
ins { text-decoration: none; }
del { text-decoration: line-through; }
/* tables still need 'cellspacing="0"' in the markup */
table { border-collapse: collapse; border-spacing: 0; }
/* end eric meyer css reset */
/** Layout **/
html, body { background:#f9f9f9; font-family:Georgia, Arial, sans-serif; color: #FFF; font-size: 12px; line-height: 21px; }
a:link, a:visited, a:active { color: #FFF; text-decoration: none; }
a:hover { text-decoration: underline; }
.clr{ clear: both; height: 0; overflow: hidden; }
#wrapper { width: 800px; margin:15% auto; position: relative; top:0; left: 0; }
/** Menu **/
#menu { float: left; position: relative; top: 0; left: 0; overflow: hidden; }
#menu .colourful { display: block; position: absolute; background: #f0ad22; height: 38px; width: 85px; top: 4px; left: -100px; }
#menu ul { margin: 0; padding: 0; list-style: none; float: left; position: relative; top: 0; left: 0; z-index: 1; }
#menu li { float: left; margin: 0 1px 0 0; }
#menu a:link, #menu a:visited, #menu a:hover, #menu a:active { color: #000; text-align: center; display: block; border: solid; border-width: 4px 0 0; line-height: 40px; width: 85px; }
#menu li a:hover, #menu li a.current { text-decoration: none; color: #fff; text-shadow: 0 0 1px #999; }
3 Создание скрипта анимации на jQuery
Листинг файла assets/menu.js
(function ($){
// готовность документа
$(function($) {
/* Устанавливаем метод анимации поумолчанию,
вы можете пропустить этот шаг если вы не хотите
использовать плагин jQuery Easing */
jQuery.easing.def = "easeInOutBack";
var // массив цветов
colors = ['#fbb92e', '#f8d52f', '#b4f62f', '#54f7a8', '#3ff7f3', '#3a97fa', '#6835f9', '#d544f6', '#f650ab'],
// кэшируем коллекции элементов, для удобства и быстроты работы
$span = $('#menu > span'),
$links = $('#menu li a'),
// индекс цвета и позиция активного пункта меню
current_pos = false,
current_index = false;
// перебираем все ссылки меню
for (var i = 0; i < $links.length; i++) {
// устанавливаем цвета границ
$links.eq(i).css('border-color', colors[i]);
// определяем текущую ссылку
if ($links.eq(i).hasClass('current')){
// устанавливаем позицию текущей ссылки
current_pos = $links.eq(i).position('#menu').left;
// устанавливаем индекс цвета текущей ссылки
current_index = i;
}
// добавление событий
$links.eq(i).data('index', i).bind({
// mouse enter
mouseenter: function(e) {
// остановка воспроизведения анимации
$span.stop();
// будующая позиция выделения
var left = $(this).position('#menu').left;
// устанавливаем цвет выделения
$span.css('background', colors[$(this).data('index')]);
// анимация передвежения выделения
$span.animate({ left: left }, 600);
},
// mouse leave
mouseleave: function(e){
// остановка воспроизведения анимации
$span.stop();
// позиция выделения поумолчанию
var left = -100;
// если меню имеет активный пункт
if (false !== current_pos) {
// обновляем параметры выделения
left = current_pos;
$span.css('background', colors[current_index]);
}
// анимация передвежения выделения
$span.animate({ left: left },600);
}
});
}
// выделяем активный пункт меню
if (false !== current_pos) {
// устанавливаем позицию выделения для активного пункта меню
$span.css('left', current_pos);
// устанавливаем цвет выделения для активного пункта меню
$span.css('background', colors[current_index]);
}
});
})(jQuery);
Ну вот обственно и все, наше красочное, анимированое jQuery меню готово!