Belarusian (беларуская мова) 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:

Тэма 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