Создаем стрелочные часы при помощи CSS3
Создатели своих веб-ресурсов часто любят устанавливать такие гаджеты как часы, честно я не понимаю смысл в этом, ведь я всегда посмотрю время на часы на руке или на ноуте, но все же такой урок имеет место быть, ведь на каждый товар есть свой покупатель. В данном уроке мы рассмотрим как создать замечательные на вид, на мой взгляд, стрелочные часы. Следует отметить, что данные часы являются экспериментом, и могут не поддерживаться некоторыми браузерами включая ранние версии старого ослика, и так, давайте приступим.
Ключевой особенностью является то, что часы учитывают часовой пояс установлен у Вас на компьютере, а как вы знаете, некоторые используют виджеты в которых уже зафиксирован часовой пояс для определенной страны, то есть получается что я, житель Украины, захожу на русский сайт, и мне отображается русское время, а не украинское. С этими часами все иначе.
Шаг 1. HTML
Для начала нам необходимо организовать простенькую разметку, в ней мы отобразим цифры для отображение на часах, все это мы обвернем в классы:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
</pre> <div class="support"></div> <div class="clock"> <div class="numbers"> <ul> <li>12</li> <li>3</li> <li>6</li> <li>9</li> </ul> </div> <div class="clockwise"></div> </div> <pre> |
Кроме этого мы добавляем классы со стрелками, как Вы уже поняли, для аналоговых часов у нас будет три стрелки.
Шаг 2. CSS
Нам необходимо определить общие параметры контейнера, кроме этого нам необходимо создать стиль самых часов, для этого мы будем использовать градиентную заливку и тени для эффекта объемности часов. Параметры border-radius позволит нам скруглить углы, установив значение 50% мы получим круг, что и необходимо нам для подложки для часов.
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 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 |
*, *:before, *:after { box-sizing: border-box; } html { height:100%; } body { background: radial-gradient(center center, circle cover, #c9c2b6, #7a726f); background: -moz-radial-gradient(center center, circle cover, #c9c2b6 0%, #7a726f 100%); background: -webkit-radial-gradient(center center, circle cover, #c9c2b6 0%, #7a726f 100%); font-family: Arial, helvetica, 'sans'; } .clock { width:193px; height:193px; border-radius:80%; margin:auto; position:absolute; top:0; right:0; bottom:0; left:0; background:#f0f1e9; box-shadow: 0 10px 20px rgba(0,0,0,0.2), inset 0 3px 0 rgba(255,255,255,0.5), inset 0 -4px 0 rgba(0,0,0,0.1), 0 2px 5px rgba(0,0,0,0.2); /* background: linear-gradient(top, #f0f1e9, #f0f1e9 100%);*/ } .clock::before { content:''; width:130px; height:130px; position:absolute; margin:auto; top:0; right:0; bottom:0; left:0; border-radius:50%; background: -webkit-linear-gradient(top, #e9eae2, #f5f5ec 100%); background: -moz-linear-gradient(top, #e9eae2, #f5f5ec 100%); background: linear-gradient(top, #e9eae2, #f5f5ec 100%); } .numbers, clockwise { width:100%; height:100%; border-radius:50%; } .numbers ul { list-style:none; } .numbers ul li { position:absolute; width:1.5em; height:1.5em; text-align:center; line-height:1.5em; font-size:1.3em; color:#a5a595; } .numbers ul li:first-child { top:0; left:50%; margin-left:-0.75em; } .numbers ul li:nth-child(2){ top:50%; right:0; margin-top:-0.75em; } .numbers ul li:nth-child(3){ left:50%; bottom:0; margin-left:-0.75em; } .numbers ul li:last-child{ top:50%; left:0; margin-top:-0.75em; } .clockwise .center, .support { position:absolute; width:10px; height:10px; border-radius:50%; background: radial-gradient(center center, circle , #ffffff, #837874 97%, #b4b2aa 100%); background: -moz-radial-gradient(center center, circle,#ffffff, #837874 97%, #b4b2aa 100%); background: -webkit-radial-gradient(center center, circle , #ffffff, #837874 97%, #b4b2aa 100%); background-position:50% -12px; box-shadow: 0 3px 5px rgba(0,0,0,0.3); } .clockwise .center { left:50%; margin-left:-5px; top:50%; margin-top:-5px; z-index:5; } .support { margin:auto; top:-260px; right:0; bottom:0; left:0; box-shadow: 0 5px 5px rgba(0,0,0,0.4), 0 -1px 2px rgba(0,0,0,0.3); } .support::before { content:''; width:4px; height:100px; background:#fff; position:absolute; z-index:-1; transform:rotate(38deg); transform-origin:50% 0%; top:5px; left:3px; background: linear-gradient(left, #f3f3f3, #fff); box-shadow: 4px 3px 3px rgba(0,0,0,0.2), inset 1px 0 4px rgba(0,0,0,0.2); } .support::after { content:''; width:4px; height:100px; background:#fff; position:absolute; z-index:-1; transform:rotate(-38deg); transform-origin:50% 0%; top:5px; left:1px; background: linear-gradient(left, #f3f3f3, #fff); box-shadow: -2px 3px 3px rgba(0,0,0,0.2), inset 1px 0 4px rgba(0,0,0,0.2); } [class*="hand-"] { border-radius: 100% 100% 5px 5px; box-shadow: 0 0 0.5em rgba(black,0.2); left: 50%; position: absolute; top: 50%; z-index: 4; box-shadow:0 5px 5px rgba(0,0,0,0.3); } .hand-second { width: 2px; top: 18px; height: 78px; background:#f16e54; transform-origin: 50% 100%; } .hand-minute { width: 6px; top:26px; margin-left:-3px; height: 88px; background:#68645b; transform-origin: 50% 80%; } .hand-hour { width: 6px; top: 56px; transform-origin: 50% 40px; margin-left:-3px; height: 50px; background:#68645b; } |
Также мы присвоили стиль для каждой стрелки, каждая из которых будет создавать эффект наложения благодаря теням.
Шаг 3. JS
Здесь все интереснее, кроме того, что нам необходимо считать временной диапазон для часов, ну и установить ход для всех стрелок часов.
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 |
var oClockAnalog = { aSecond: [], dtDate: new Date(), iCurrSecond: -1, iHourRotation: -1, iMinuteRotation: -1, iStepSize: 10, iTimerAnimate: setInterval("oClockAnalog.fAnimate()", 20), iTimerUpdate: setInterval("oClockAnalog.fUpdate()", 1000), fAnimate: function() { if (this.aSecond.length > 0) { this.fRotate("analogsecond", this.aSecond[0]); this.aSecond = this.aSecond.slice(1); } }, fGetHour: function() { var iHours = this.dtDate.getHours(); if (iHours > 11) { iHours -= 12; } return Math.round((this.dtDate.getHours() * 30) + (this.dtDate.getMinutes() / 2) + (this.dtDate.getSeconds() / 120)); }, fGetMinute: function() { return Math.round((this.dtDate.getMinutes() * 6) + (this.dtDate.getSeconds() / 10)); }, fInit: function() { this.iHourRotation = this.fGetHour(); this.fRotate("analoghour", this.iHourRotation); this.iMinuteRotation = this.fGetMinute(); this.fRotate("analogminute", this.iMinuteRotation); this.iCurrSecond = this.dtDate.getSeconds(); this.fRotate("analogsecond", (6 * this.iCurrSecond)); }, fRotate: function(sID, iDeg) { var sCSS = ("rotate(" + iDeg + "deg)"); $("#" + sID).css({ '-moz-transform': sCSS, '-o-transform': sCSS, '-webkit-transform': sCSS }); }, fStepSize: function(iTo, iFrom) { var iAnimDiff = (iFrom - iTo); if (iAnimDiff > 0) { iAnimDiff -= 360; } return iAnimDiff / this.iStepSize; }, fUpdate: function() { // update time this.dtDate = new Date(); // hours var iTemp = this.fGetHour(); if (this.iHourRotation != iTemp) { this.iHourRotation = iTemp; this.fRotate("analoghour", iTemp); } // minutes iTemp = this.fGetMinute(); if (this.iMinuteRotation != iTemp) { this.iMinuteRotation = iTemp; this.fRotate("analogminute", iTemp); } // seconds if (this.iCurrSecond != this.dtDate.getSeconds()) { var iRotateFrom = (6 * this.iCurrSecond); this.iCurrSecond = this.dtDate.getSeconds(); var iRotateTo = (6 * this.iCurrSecond); // push steps into array var iDiff = this.fStepSize(iRotateTo, iRotateFrom); for (var i = 0; i < this.iStepSize; i++) { iRotateFrom -= iDiff; this.aSecond.push(Math.round(iRotateFrom)); } } } }; ClockInit(); |
Вот и все. Готово!
Материал взят из зарубежного источника. И представлен исключительно в ознакомительных целях.
Читайте также:
Опубликовал Cooper 26.08.2013 в 14:28, в категории Веб-дизайн. Вы можете следить за комментариями через RSS 2.0. Вы можете перейти в конец записи и оставить комментарий. Пинги запрещены. |