Навигация для сайта в стиле iOS на jQuery
Компания Apple стала весьма популярна благодаря своим чудо-гаджетам. Это не удивительно, ведь они действительно хороши, новые инновации, скорость работы, портативность-это лишь малая верхушка айсберга устройств данного гиганта. Быстрота отклика операционной системы iOS не оставит равнодушным пользователя. Но что если применить технологию перелистывания слайдов с навигацией для сайта. В данном уроке мы рассмотрим как это можно осуществить. Данный эффект отлично подойдет для оформления портфолио, или прочих креативных проектов.
Данный эффект будет достигнут с помощью CoffeeScript – новая jQuery-библиотека, основанная на javascript. CoffeeScript предлагает вам понятный синтаксис, напоминающий нечто вроде Ruby и Python. Если вы не знакомы с данными языками, не беспокойтесь – эти знания вам не потребуются. Тем не менее, вы должны быть знакомы с javascript, вам следовало бы понимать принцип работы.
Шаг 1. HTML
Давайте начнем с верстки HTML для нашего экрана загрузки. Как обычно, будем использовать документ HTML5 с таблицами стилей в шапке, и включенным JS перед закрывающим тегом body.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
Создаем навигацию в стиле iOS с помощью jQuery | Демонстрация для сайта RUDEBOX <!-- Our CSS stylesheet file --> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <section id="homeScreen"> <div id="mask"> <div id="allScreens"></div> </div> <div id="dock"></div> </section> <!-- javascript --><script type="text/javascript" src="http://code.jquery.com/jquery-1.6.3.min.js"></script> <script type="text/javascript" src="assets/js/touchable.js"></script><script type="text/javascript" src="assets/js/coffee-script.js"></script> <script type="text/javascript">// <![CDATA[ // ]]></script> |
У нас есть раздел #homeScreen, который и будет основным контейнером для нашего эксперимента. Внутри будет #mask, где используется overflow:hidden, чтобы в тот момент был отображен только экран загрузки. Div #allScreens внутри него (как видно по названию) будет содержать все динамически сгенерированные div’ы .screen с иконками.
Как ранее было сказано, CoffeeScript требует дополнительного этапа компиляции, который позволит вам конвертировать исходный код в javascript. Вы сможете делать это посредством coffeescript для node.js, либо посредством coffeescript.exe для Windows, который отлично работает отдельно. Что касается маленьких скриптов, вы также можете включить компилятор напрямую в страницу, и вписывать нужный код в тег «script».
Шаг 2. CSS
С помощью наших стилей мы создадим позиционирование наших изображений, также мы создадим стили подписей изображений, и зададим количество изображений на одном слайде.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
*{ margin:0; padding:0; } html{ background: #000000 url(header.jpg) no-repeat center top; } body{ color:#fff; min-height:600px; font:14px/1.3 'Segoe UI',Arial, sans-serif; } a, a:visited { text-decoration:none; outline:none; color:#54a6de; } a:hover{ text-decoration:underline; } section, footer{ display: block; } #homeScreen{ width:890px; height:930px; padding: 1px; margin: 0 auto 30px; background:url('../img/background.png') no-repeat left bottom; } #mask{ width: 632px; height:480px; position: relative; overflow: hidden; margin: 180px auto -150px; } #allScreens{ height:100%; top:0; left:0; position:absolute; cursor:move; } .screen{ width: 332px; float:left; } #dock .dockicon, .screen .icon{ float:left; width:60px; height:60px; background-repeat: no-repeat; margin: 25px; position: relative; } /* Displaying the title attribute below the icon: */ .screen .icon:after{ bottom: -25px; color: white; content: attr(title); font-size: 12px; height: 20px; left: -20px; overflow: hidden; position: absolute; text-align: center; white-space: nowrap; width: 100px; text-shadow: 0 0 3px #222; } #dock{ height: 70px; margin: 60px auto; width: 332px; } #dock .dockicon:after{ border-radius: 50px/10px; bottom: 7px; box-shadow: 0 5px 2px #000000; content: ""; height: 1px; position: absolute; width: 58px; } #indicators{ text-align:center; list-style: none; } #indicators li{ border-radius:50%; display: inline-block; margin:7px; width:6px; height:6px; background-color:white; opacity:0.6; } #indicators li.active{ opacity:1; background-color:#00A2D6; box-shadow: 0 0 3px #00A2D6, 0 0 1px #51CFF9 inset; } |
Шаг 3. CoffeeScript
Теперь давайте приступим к написанию простого класса – Icon.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# The Icon class. class Icon # The constructor. The -> arrow signifies # a function definition. constructor: (@id, @title) -> # @ is synonymous for "this". The id and title parameters # of the constructor are automatically added as this.id and this.title # @markup holds the HTML of the icon. It is # transformed to this.markup behind the scenes. @markup = "</pre> <div class="icon" style="background-image: url('assets/img/icons/#{@id}.png');" title="#{@title}"></div> <pre> " |
Объекты данного класса будут представлять иконки на экране загрузки. Каждая иконка будет обозначена параметром, содержащим HTML-код, нужный для ее отображения. Вы можете видеть, что функции в CoffeeScript определяются стрелками (->), а параметры функции указаны в левой части, в скобках. Учтите, что здесь комментарии начинают с символа #. Вы можете использовать три ### для определения многострочных комментариев.
Теперь определим класс для иконок панели. Он будет очень похожим на класс icon, мы просто расширим его:
1 2 3 4 5 6 7 8 9 10 11 |
# The DockIcon class inherits from Icon class DockIcon extends Icon constructor: (id, title)-> # This calls the constructor if Icon super(id, title) # Changing the class name of the generated HTML @markup = @markup.replace("class='icon'","class='dockicon'") |
Используя super() мы можем вызвать конструктор иконок и инициализировать параметры верстки. Нам можно нужно заменить имя класса. Мы разделим экран загрузки на отдельные div’ы .screen, и у каждого из них будет собственный набор иконок. Давайте рассмотрим его класс:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# The Screen Class class Screen # Function arguments can have default values constructor: (icons = [])-> @icons = icons attachIcons: (icons = [])-> Array.prototype.push.apply(@icons, icons) generate: -> markup = [] # Looping through the @icons array markup.push(icon.markup) for icon in @icons # The last line of every function is implicitly returned "</pre> <div class="screen">#{markup.join('')}</div> <pre> " |
Вместо параметров верстки, мы будем использовать метод generate(), который вернет нам HTML-код. Учтите то, как мы зацикливаем массив, такой метод называется включение.
Теперь нам нужен класс, который соберет все вместе, а также будет контролировать переходы между экранами. Вот так это всё должно выглядеть:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
class Stage # The width of our "device" screen. This is # basically the width of the #mask div. screenWidth: 332 constructor: (icons)-> @currentScreen = 0 @screens = [] # Calculating the number of screens # necessary to display all the icons num = Math.ceil(icons.length / 9) i = 0 while num-- # we pass a slice of the icons array s = new Screen(icons[i...i+9]) # adding the screen to the local screens array @screens.push(s) i+=9 # This method populates the passed element with HTML addScreensTo: (element)-> # We are using the jQuery library from within CS: @element = $(element) @element.width(@screens.length*@screenWidth) for screen in @screens @element.append(screen.generate()) addIndicatorsTo: (elem)-> # This method creates the small circular # indicators. Also using jQuery @ul = $(elem) for screen in @screens @ul.append('</pre> <ul> <li>') @ul.find('li:first').addClass('active'); # ... More methods go here ... |
Stage берёт массив иконок в конструкторе. Далее производится вычисление, сколько потребуется экранов, и создается объект для каждого из них, заполняя его частью массива иконок. Теперь у нас есть разметка для всех элементов на странице, но все еще отсутствуют методы контроля переходов между отрезками. Вы можете видеть их ниже (оставшийся код класса Stage):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
goTo: (screenNum)-> # This method animates the allScreen div in # order to expose the needed screen in #mask if @element.is(':animated') return false # if this is the first or last screen, # run the end of scroll animation if @currentScreen == screenNum # Parallel assignment: [from, to] = ['+=15','-=15'] if @currentScreen != 0 [from, to] = [to, from] # Tell the user there aren't any more screens: @element.animate( { marginLeft : from }, 150 ) .animate( { marginLeft : to }, 150 ) else # If everything is ok, animate the transition between the screens. # The fat arrow => is a function that preserves the context of "this" @element.animate( { marginLeft:-screenNum*@screenWidth }, => @currentScreen = screenNum ) @ul.find('li').removeClass('active').eq(screenNum).addClass('active'); next: -> toShow = @currentScreen+1 # If there is no next screen, show # the last one if toShow == @screens.length toShow = @screens.length - 1 @goTo(toShow) previous: -> toShow = @currentScreen-1 # If there is no previous screen, # show the first one if toShow == -1 toShow = 0 @goTo(toShow) |
Как метод next(), так и previous() вызывают goTo() внутренне, проводя номер экрана (начиная от 0). Метод goTo() анимирует div #allScreen для отображения нужного экрана.
Шаг 4. jQuery
Нам осталось лишь закрепить функцию к событию document.ready. Для этого мы воспользуемся jQuery.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# This is equivalent to $(function(){}): $ -> # You can skip the comma if it's on the end of a line: allIcons = [ new Icon('Photos', 'Photo Gallery'), new Icon('Maps', 'Google Maps') new Icon('Chuzzle', 'Chuzzle'), new Icon('Safari', 'Safari') new Icon('Weather', 'Weather'), new Icon('nes', 'NES Emulator') new Icon('Calendar', 'Calendar'), new Icon('Clock', 'Clock') new Icon('BossPrefs', 'Boss Prefs'), new Icon('Chess', 'Chess') new Icon('Mail', 'Mail'), new Icon('Phone', 'Phone') new Icon('SMS', 'SMS Center'), new Icon('Camera', 'Camera') new Icon('iPod', 'iPod'), new Icon('Calculator', 'Calculator') new Icon('Music', 'Music'), new Icon('Poof', 'Poof') new Icon('Settings', 'Settings'), new Icon('YouTube', 'Youtube') new Icon('psx4all', 'PSx4All'), new Icon('VideoRecorder', 'Record Video') new Icon('Installer', 'Installer'), new Icon('Notes', 'Notes') new Icon('RagingThunder', 'RagingThunder'), new Icon('Stocks', 'Stocks') new Icon('genesis4iphone', 'Genesis'), new Icon('snes4iphone', 'SNES Emulator') new Icon('Calendar', 'Calendar'), new Icon('Clock', 'Clock') new Icon('Photos', 'Photo Gallery'), new Icon('Maps', 'Google Maps') ] dockIcons = [ new DockIcon('Camera', 'Camera') new DockIcon('iPod', 'iPod') new DockIcon('Calculator', 'Calculator') ] allScreens = $('#allScreens') # Using the Touchable plugin to listen for # touch based events: allScreens.Touchable(); # Creating a new stage object stage = new Stage(allIcons) stage.addScreensTo(allScreens) stage.addIndicatorsTo('#indicators') # Listening for the touchablemove event. # Notice the callback function. Braces on # function calls are optional allScreens.bind 'touchablemove', (e,touch)-> stage.next() if touch.currentDelta.x < -5 stage.previous() if touch.currentDelta.x > 5 # Adding the dock icons: dock = $('#dock') for icon in dockIcons dock.append(icon.markup) |
CoffeeScript – интересный язык, который может сделать разработку для браузера легче. Можете рассчитывать на то, что кода придется писать на 50% меньше, чем в чистом javascript. Хотя вряд ли можно сказать, что CoffeeScript вскоре может заменить javascript, так как данная система жертвует возможностями в целях облегчения кода. CS вероятно не подойдет для всех ваших проектов.
Материал взят из зарубежного источника. И представлен исключительно в ознакомительных целях.
Читайте также:
Опубликовал Cooper 30.05.2012 в 18:32, в категории Плагины. Вы можете следить за комментариями через RSS 2.0. Вы можете перейти в конец записи и оставить комментарий. Пинги запрещены. |