Table of Contents
Step 1: HTML
Step 2: CSS
Today’s theme:
Night theme:
day.css:
Night.css:
Step 3: Style Switcher.php
Step 4: jQuery Content
加载样式表:
完成!
Home Web Front-end JS Tutorial Create an Incredible jQuery Style Switcher: A Step-by-Step Guide

Create an Incredible jQuery Style Switcher: A Step-by-Step Guide

Sep 02, 2023 am 10:13 AM

In this tutorial, I will show you how to create a style switcher using jQuery and PHP. The end result will be an unobtrusive and fully degradable dynamic style switcher that will be fast and easy to implement.

创建令人难以置信的 jQuery 样式切换器:分步指南

Step 1: HTML

First we need to create the basic HTML file and save it as 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>
Copy after login

You'll see some PHP underneath the header title attribute. It's very simple - all it does is check for a cookie called "style" - if it exists, it assigns it to a local variable (also called "style"), if the cookie doesn't exist, it Assign the default theme ("day") to the $style variable. This variable is then echoed in the link element's href attribute (href="css/<?php echo $style ?>.css").

You will see the style switcher div included in the HTML above. There is no need to use JavaScript to add this as the method we use will allow the style switcher to work when JavaScript is disabled. Both links (night and day) take the user to a file named style-switcher.php with a query string appended specifying the corresponding theme (e.g. href="style-switcher.php?style=day "). < /p>

I also called a jQuery plug-in called styleSwitcher. This hasn't been developed yet (well, it will be by the time you read this), so wait! ...we will write this plugin in step 4 of this tutorial.

Step 2: CSS

Now, we need to create a few CSS stylesheets for the HTML. I decided to create just two stylesheets - one themed "Day" and one themed "Night" and I have named them appropriately. (Day.css and Night.css)

Today’s theme:

创建令人难以置信的 jQuery 样式切换器:分步指南

Night theme:

创建令人难以置信的 jQuery 样式切换器:分步指南

It's better to start with one style and then copy all selectors to the alternative stylesheet - then all that needs to be changed are the various CSS rules and declarations. Obviously you can have as many style sheets as you want, but in this tutorial we'll use two for illustration purposes. And day and night get along great together as a duo!

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;}
Copy after login

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;
}
Copy after login

This isn't really a CSS tutorial, so I won't delve into any of the above, but if you have any questions, feel free to ask in the comments section. Yes, I know older browsers don't support min-width! ;)

Step 3: Style Switcher.php

This is where we write the core functionality of the style switcher. It's really just a few lines of very basic PHP code. You should create a new file called "style-switcher.php" and copy the following content into it:

<?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']);
	}
?>
Copy after login

So what the code above does is assign the "style" GET variable to the local $style variable. In other words, it will take the value of the style attribute in the query string (style-switcher.php?style=day). It then sets a cookie called "style" (which lasts for one week) - we will be able to retrieve this cookie on the main index.php using the code shown in step 1 (remember that little one in head Block PHP?). Next, it checks if "js" is appended to the query string. If it is, then we know that JavaScript (which we haven't written yet) has requested this PHP script. The else condition occurs when the user does not have JavaScript enabled and redirects the user to the referrer (i.e. the page they just came from) - this will become clearer once we write the jQuery content!

Step 4: jQuery Content

You can stop right here if you want! ...the solution so far will work perfectly, but as I said in the introduction, we're going to make it even cooler with some jQuery power! Not only will we allow users to change themes without refreshing the page, but we'll also be adding a really cool fade effect... I mean, what type of jQuery tutorial would this be without a fade! ? ! ?

Obviously this is all possible without creating a plugin, but I think it will be a great learning experience for all of you, and it allows us to adapt or transfer code quickly and easily.

First, let's create a file called "styleswitcher.jquery.js".

Creating a new plugin in jQuery is very simple; all that is required is the following code:

jQuery.fn.styleSwitcher = function(){
	// The code goes here...
}
Copy after login

So, first we want to specify what happens when one of the stylesheet links (the link in div#style-switcher) is clicked:

/* "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;
});
Copy after login

加载样式表:

现在我们需要编写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();
					});
				});
			});
		});
}
Copy after login

我希望评论能充分解释这一点。细心的你会注意到我们正在调用一个当前未定义的函数(cssDummy.check())。别担心,因为这是下一步......

cssDummy:

我们需要一种方法来测试样式表是否已加载。如果它已经加载,那么我们可以让覆盖层 div 消失,但如果它没有加载,我们必须继续检查,直到它加载。我在网上进行了一些搜索,找到了测试此类事情的可靠方法。它涉及测试虚拟元素的计算宽度。该元素的宽度将在 CSS 中定义 - 因此,当样式表加载时,计算出的元素宽度将仅等于 CSS 中定义的宽度。我希望您现在明白为什么我们必须在每个 CSS 文件中包含“#dummy-element”规则...

所以,这里是:

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);
	}
}
Copy after login

并且,在插件的最后,我们将调用 cssDummy.init 函数:

cssDummy.init();
Copy after login

我们完成了!整个插件现在看起来像这样:

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();
}
Copy after login

我们现在可以像这样调用 jQuery 插件:

$('#style-switcher a').styleSwitcher();
Copy after login

完成!

如果您不确定文件结构,请下载 src 文件来查看。我希望您喜欢阅读本教程。一如既往,如果您有任何疑问,请随时在下面提问!如果您喜欢这篇文章,请挖掘它!

The above is the detailed content of Create an Incredible jQuery Style Switcher: A Step-by-Step Guide. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

See all articles