Russian (Pусский) translation by Alex Grigorovich (you can also view the original English article)
В этом уроке я покажу вам, как создать стильный переключатель с использованием jQuery и PHP. Конечным результатом будет ненавязчивый и адаптивный стильный переключатель, который будет быстро и легко использовать.
Шаг 1: HTML
Во-первых, нам нужно создать наш основной HTML-файл и сохранить его как index.php:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Style Switcher</title> <?php // Checks for, and assigns cookie to local variable: if(!empty($_COOKIE['style'])) $style = $_COOKIE['style']; // If no cookie is present then set style as "day" (default): else $style = 'day'; ?> <!-- StyleSheet --> <link id="stylesheet" type="text/css" href="css/<?php echo $style ?>.css" rel="stylesheet" /> <!-- jQuery --> <script type="text/javascript" src="js/jquery.js"></script> <!-- Our plugin --> <script type="text/javascript" src="js/styleswitcher.jquery.js"></script> </head> <body> <div id="container"> <h1>Style-Switcher Example</h1> <ul id="nav"> <li><a href="#">Home</a></li> <li><a href="#">About</a></li> <li><a href="#">Services</a></li> <li><a href="#">Products</a></li> <li><a href="#">Links</a></li> <li><a href="#">Contact</a></li> </ul> <div id="banner"></div> <div id="content"> <h2>NETTUTS Tutorial Example</h2> <p>Page content...</p> </div> <div id="foot"> <p>Footer stuff...</p> </div> <!-- StyleSheet selection: --> <div id="style-switcher"> <h4>Choose your style:</h4> <ul> <li id="day"><a href="style-switcher.php?style=day">Day</a></li> <li id="night"><a href="style-switcher.php?style=night">Night</a></li> </ul> </div> </div> <script type="text/javascript"> $('#style-switcher a').styleSwitcher(); // Calling the plugin... </script> </body> </html>
Вы увидите, что там есть код PHP, который находится чуть ниже атрибута title в заглавной части страницы. Это очень просто - все, что тут происходит, это проверка на наличие куки под названием «style» - если он существует, он закрепляется к текущей переменной (также называемой «lestz»), а если файл cookie не существует, то тема назначается по умолчанию ( «day») к переменной $style
. Затем эта переменная будет вызвана в атрибуте href ссылки (href="css /.сss"/?php echo $style ?>.css")
.
Вы увидите, что слой div style-switcher приведен выше в нашем HTML-коде. Не нужно добавлять его с помощью JavaScript, потому что метод, который мы используем, позволит работать переключателю стиля, даже когда JavaScript отключен. Две ссылки (night и day) переносят пользователя в файл под названием style-switcher.php с добавленной строкой в запросе, определяющей соответствующую тему (например, href="style-switcher.php?style=day"
).
Я также назвал плагин для jQuery styleSwitcher. Это еще в стадии разработки (ну, мы закончим к тому моменту, когда вы прочтете статью), так что держитесь! ... Мы будем писать этот плагин на 4 шаге урока.
Шаг 2: CSS
Теперь нам нужно создать пару таблиц стилей CSS для нашего HTML. Я решил создать только две таблицы - у вас будет тема «Day», а у другой будет тема «Night», и я назвал их соответствующим образом. (day.css & night.css) (day.css & night.css)
Тема Day:

Тема Night:

Лучше всего создать один стиль, а затем скопировать все селекторы в другую таблицу - и тогда все, что нужно изменить, - это добавить различные правила и конструкции CSS. Очевидно, что у вас может быть столько таблиц, сколько хотите, но в этом уроке мы используем только две. К тому же день и ночь хорошо сочетаются!
day.css:
#dummy-element{width:2px;} /* Necessary to check if StyleSheet has loaded */ /* Quick Reset */ body,ul,ol,li,img,form,p,h1,h2,h3,h4,h5,h6,blockquote { margin: 0; padding: 0; border: none; list-style: none; font-weight: normal; } /* General / Header */ body {background: #98beeb url(../img/day-body-bg.jpg) repeat-x; } #container { width: 60%; margin: 0 auto; min-width: 400px; max-width: 800px; position: relative; } h1 { text-align: left; text-transform: uppercase; color: white; font-size: 1.4em; padding: 45px 30px 10px 30px; } /* Navigation */ #nav { padding: 5px 5px 0 0; overflow: hidden; } #nav li {display: inline;} #nav a { float: left; color: #6195ce; font-weight: bold; text-decoration: none; padding: 3px 6px; margin-left: 5px; background: white; } #nav a:hover {color: #2c5a8c;} /* Banner */ #banner { height: 125px; background: url(../img/day-banner.jpg) center; border: 5px solid white; clear: both; } /* Content Area */ #content { border: 10px solid white; background: white; color: #2c5a8c; margin: 5px 0; } #content a {font-weight: bold;} #content a:hover {text-decoration: underline;} h2 { padding: 0.3em 0; font-size: 1.4em; } p {padding: 0.3em 0;} /* Footer */ #foot { background: white; color: #1f3a57; text-align: center; border: 10px solid white; clear: both; } #foot a { text-decoration: none; font-weight: bold; color: #2c5a8c; } #foot a:hover {text-decoration: underline;} /* Style-Switcher */ #style-switcher { position: absolute; width: 100%; top: 0; left: 0; right: 0; height: 34px; background: #79a3cc url(../img/day-ss-bg.jpg); border-bottom: 1px solid white; } #style-switcher ul { border-right: 1px solid white; float: right; } #style-switcher h4 { display: inline; color: #153c67; font-weight: bold; line-height: 34px; padding: 0 10px; float: left; border-left: 1px solid white; } #style-switcher li {display: inline;} #style-switcher li a { float: left; line-height: 26px; color: white; background: #90a6bb; text-decoration: none; padding: 0 13px; display: inline; margin: 4px 4px 4px 0; } #style-switcher li a:hover {background: #3a5a7c;}
night.css:
#dummy-element{width:2px;} /* Necessary to check if StyleSheet has loaded */ /* Quick Reset */ body,ul,ol,li,img,form,p,h1,h2,h3,h4,h5,h6,blockquote { margin: 0; padding: 0; border: none; list-style: none; font-weight: normal; } /* General / Header */ body { font-family: Calibri,"Arial Narrow",Arial,Sans-Serif; background: #072952 url(../img/night-body-bg.jpg) repeat-x; } #container { width: 60%; margin: 0 auto; min-width: 400px; max-width: 800px; position: relative; } h1 { text-align: left; text-transform: uppercase; color: white; font-size: 1.4em; padding: 45px 30px 10px 30px; font-family: "Times New Roman", Times, serif; } /* Navigation */ #nav { padding: 5px 5px 0 0; overflow: hidden; } #nav li {display: inline;} #nav a { float: left; color: #010e2e; font-weight: bold; text-decoration: none; padding: 8px 6px 3px 6px; font-size: 0.8em; text-transform: uppercase; font-weight: 700; margin-left: 5px; background: white url(../img/night-nav-bg2.jpg) repeat-x; } #nav a:hover {color: #2c5a8c;} /* Banner */ #banner { height: 125px; background: url(../img/night-banner.jpg) center; border: 5px solid white; clear: both; } /* Content Area */ #content { color: white; margin: 20px 0; padding: 5px 0; border-top: 4px double white; border-bottom: 4px double white; font-family: "Times New Roman", Times, serif; } #content a {font-weight: bold;} #content a:hover {text-decoration: underline;} h2 { padding: 0.3em 0; font-size: 1.4em; } p {padding: 0.3em 0;} /* Footer */ #foot { color: white; font-size: 0.8em; clear: both; } #foot p { text-align: center; padding: 0; } #foot a { text-decoration: none; font-weight: bold; color: white; } #foot a:hover {text-decoration: underline;} /* Style-Switcher */ #style-switcher { position: absolute; width: 100%; top: 0; left: 0; right: 0; height: 34px; } #style-switcher ul {float: left;} #style-switcher h4 { display: inline; color: white; font-weight: bold; line-height: 34px; padding: 0 10px; float: left; } #style-switcher li {display: inline;} #style-switcher li a { float: left; line-height: 34px; color: white; text-decoration: none; padding: 0 4px; margin-left: 5px; display: inline; } #style-switcher li a:hover { background: white; color: #13181c; background: white url(../img/night-ss-bg.jpg) repeat-x left bottom; }
На самом деле это не урок по CSS, поэтому я не буду разбираться со всеми вопросами, но если они у вас есть, пожалуйста, не стесняйтесь, задавайте их в разделе комментариев. И да, я знаю, что свойство min-width не поддерживается в старых браузерах! ;) ;)
Шаг 3: style-switcher.php
Здесь мы пишем основные функции переключателя стиля. На самом деле это всего лишь несколько строк очень простого кода PHP. Вы должны создать новый файл под названием «style-switcher.php» и скопировать в него следующее:
<?php $style = $_GET['style']; setcookie("style", $style, time()+604800); // 604800 = amount of seconds in one week if(isset($_GET['js'])) { echo $style; } else { header("Location: ".$_SERVER['HTTP_REFERER']); } ?>
Итак, вышеприведенный код присваивает значение переменной GET $style
локальной переменной $style. Другими словами, скрипт примет значение свойства стиля из строки запроса (style-switcher.php?style=day). Затем он установит cookie (на одну неделю), называемый «style», - мы сможем запросить этот файл cookie через наш основной файл index.php с помощью кодом, созданного в шаге № 1 (помните, это небольшая часть PHP в head
?). Затем скрипт проверяет, добавляется ли «js» к строке запроса. Если это так, то мы узнаем, что запрос произошел с помощью JavaScript (который мы еще не создали). Условие else выполняется, когда пользователь не включил JavaScript и использует перенаправление (т. е. страницу, с которой они только что пришли) - это станет более понятным, как только мы напишем код jQuery!
Шаг 4: код jQuery
Если хотите,можете остановиться прямо здесь!... Наше решение будет работать отлично, но, как я говорил во вступлении, мы сделаем его еще круче с помощью jQuery! Мы не только позволим пользователю поменять свою тему, не обновляя страницу, но мы также собираемся добавить крутой эффект угасания ... Я имею в виду, что бы это был за урок jQuery без эффекта угасания
Это все возможно без создания плагина, но я думаю, это будет хорошая практика для всех вас, а также позволяет быстро и легко адаптировать и передавать код.
Прежде всего, давайте создадим файл под названием «styleswitcher.jquery.js».
Создание нового плагина в jQuery чрезвычайно просто; все, что требуется, это написать следующий код:
jQuery.fn.styleSwitcher = function(){ // The code goes here... }
Итак, сначала мы хотим указать, что происходит, когда нажимается одна из ссылок таблицы стилей (т.е. те ссылки, которые находятся в слое div#style-switcher
):
/* "this" refers to each instance of the selected element, * So, if you were to call the plugin like this: * $('a').styleSwitcher(); then the following would occur * when clicking on any anchor within the document: */ $(this).click(function(){ // We're passing this element object through to the // loadStyleSheet function. loadStyleSheet(this); // And then we're returning false. return false; });
loadStyleSheet:
Теперь нам нужно написать функцию loadStyleSheet
:
function loadStyleSheet(obj) { // Append new div to body: $('body').append('<div id="overlay" />'); // Give body a height of 100% (to fix IE6 issue): $('body').css({height:'100%'}); // Select newly created div and apply some styles: $('#overlay') .css({ display: 'none', position: 'absolute', top:0, left: 0, width: '100%', height: '100%', zIndex: 1000, background: 'black url(img/loading.gif) no-repeat center' }) // Now fade in the div (#overlay): .fadeIn(500,function(){ // The following will happen when the div has finished fading in: // Request PHP script (obj.href) with appended "js" query string item: $.get( obj.href+'&js',function(data){ // Select link element in HEAD of document (#stylesheet) and change href attribute: $('#stylesheet').attr('href','css/' + data + '.css'); // Check if new CSS StyleSheet has loaded: cssDummy.check(function(){ // When StyleSheet has loaded, fade out and remove the #overlay div: $('#overlay').fadeOut(500,function(){ $(this).remove(); }); }); }); }); }
Надеюсь, что комментарии объяснили этот процесс достаточно. Вы заметите, что мы вызываем в данный момент неопределенную функцию (cssDummy.check ()
). Но не волнуйтесь, об этом в следующем шаге ...
cssDummy:
Нам нужен способ, чтобы проверить, загружена ли таблица стилей. Если это так, мы скроем перекрывающий слой, но, если его нет, то нам нужно продолжать проверку, пока он не загрузится. Я нашел в сети надежный способ тестирования. Он включает в себя проверку значения ширины фиктивного элемента. Ширина этого элемента будет определена в CSS - и поэтому ширина элемента будет равна ширине, определенной в CSS, если таблица будет загружена. Надеюсь, теперь вы поймете, почему мы должны были включить правило "#dummy-element в каждый файл CSS ...
Итак, вот оно:
var cssDummy = { init: function(){ // Appends "dummy-element" div to body: $('<div id="dummy-element" style="display:none" />').appendTo('body'); }, check: function(callback) { // Checks if computed with equals that which is defined in the StyleSheets (2px): if ($('#dummy-element').width()==2) callback(); // If it has not loaded yet then simple re-initiate this // function every 200 milliseconds until it had loaded: else setTimeout(function(){cssDummy.check(callback)}, 200); } }
В конце нашего плагина мы вызовем функцию cssDummy.init
:
cssDummy.init();
Все готово! Теперь плагин выглядит так:
jQuery.fn.styleSwitcher = function(){ $(this).click(function(){ loadStyleSheet(this); return false; }); function loadStyleSheet(obj) { $('body').append('<div id="overlay" />'); $('body').css({height:'100%'}); $('#overlay') .css({ display: 'none', position: 'absolute', top:0, left: 0, width: '100%', height: '100%', zIndex: 1000, background: 'black url(img/loading.gif) no-repeat center' }) .fadeIn(500,function(){ $.get( obj.href+'&js',function(data){ $('#stylesheet').attr('href','css/' + data + '.css'); cssDummy.check(function(){ $('#overlay').fadeOut(500,function(){ $(this).remove(); }); }); }); }); } var cssDummy = { init: function(){ $('<div id="dummy-element" style="display:none" />').appendTo('body'); }, check: function(callback) { if ($('#dummy-element').width()==2) callback(); else setTimeout(function(){cssDummy.check(callback)}, 200); } } cssDummy.init(); }
Мы можем вызвать плагин jQuery следующим образом:
$('#style-switcher a').styleSwitcher();
Вывод!
Если вы не уверены в структуре файлов, загрузите исходники файлов, чтобы их посмотреть. Надеюсь, вам понравился этот урок. Как всегда, если у вас есть вопросы, не стесняйтесь, задавайте их в комментариях! Если вам понравилось наша статья, пожалуйста, поделитесь ею в Digg!
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Update me weeklyEnvato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!
Translate this post