0

0

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

WBOY

WBOY

发布时间:2023-09-02 10:13:05

|

653人浏览过

|

来源于php中文网

原创

在本教程中,我将向您展示如何使用 jquery 和 php 创建样式切换器。最终结果将是一个不引人注目且完全可降解的动态风格切换器,它将快速且易于实现。

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

第 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。它非常简单 - 它所做的只是检查一个名为“style”的 cookie - 如果存在,则将其分配给本地变量(也称为“style”),如果 cookie 存在,它将默认主题(“day”)分配给 $style 变量。然后,该变量在链接元素的 href 属性中回显(href="css/<?php echo $style ?>.css")。

您将看到样式切换器 div 包含在上面的 HTML 中。无需使用 JavaScript 添加此内容,因为我们使用的方法将允许样式切换器在 JavaScript 禁用时工作。这两个链接(夜间和白天)将用户带到名为 style-switcher.php 的文件,其中附加了指定相应主题的查询字符串(例如 href="style-switcher.php?style=day")。

我还调用了一个名为 styleSwitcher 的 jQuery 插件。这还没有开发出来(好吧,当你读到这篇文章时它已经开发出来了),所以等等! ...我们将在本教程的第 4 步中编写此插件。

第 2 步:CSS

现在,我们需要为 HTML 创建几个 CSS 样式表。我决定只创建两个样式表 - 一个主题为“白天”,另一个主题为“夜晚”,并且我已对它们进行了适当的命名。 (白天.css 和夜晚.css)

当天主题:

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

夜晚主题:

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

最好从一种样式开始,然后将所有选择器复制到替代样式表 - 然后需要更改的只是各种 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;}

夜晚.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 教程,因此我不会深入研究上述任何内容,但如果您有任何疑问,请随时在评论部分提问。是的,我知道旧版浏览器不支持最小宽度! ;)

第3步:样式切换器.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']);
	}
?>

因此,上面的代码所做的是将“style”GET 变量分配给本地 $style 变量。换句话说,它将采用查询字符串中样式属性的值 (style-switcher.php?style=day)。然后它设置一个名为“style”的 cookie(持续一周) - 我们将能够使用步骤 1 中显示的代码在主 index.php 上检索此 cookie(还记得 head 中的那一小块 PHP 吗?) 。接下来,它检查“js”是否附加到查询字符串中。如果是,那么我们就知道 JavaScript(我们还没有编写)已经请求了这个 PHP 脚本。当用户没有启用 JavaScript 并将用户重定向到引用者(即他们刚刚来自的页面)时,就会出现 else 条件 - 一旦我们编写了 jQuery 内容,这一点就会变得更加清晰!

‎ Gemini Storybook
‎ Gemini Storybook

Google Gemini推出的AI绘本生成工具

下载

第 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函数:

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:

我们需要一种方法来测试样式表是否已加载。如果它已经加载,那么我们可以让覆盖层 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);
	}
}

并且,在插件的最后,我们将调用 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();

完成!

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

<script type="text/javascript"> <!--digg_url = "post permalink (not digg url)"; // --></script>

<script src="https://digg.com/tools/diggthis.js" type="text/javascript"></script>

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

WorkBuddy
WorkBuddy

腾讯云推出的AI原生桌面智能体工作台

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
TypeScript类型系统进阶与大型前端项目实践
TypeScript类型系统进阶与大型前端项目实践

本专题围绕 TypeScript 在大型前端项目中的应用展开,深入讲解类型系统设计与工程化开发方法。内容包括泛型与高级类型、类型推断机制、声明文件编写、模块化结构设计以及代码规范管理。通过真实项目案例分析,帮助开发者构建类型安全、结构清晰、易维护的前端工程体系,提高团队协作效率与代码质量。

76

2026.03.13

Python异步编程与Asyncio高并发应用实践
Python异步编程与Asyncio高并发应用实践

本专题围绕 Python 异步编程模型展开,深入讲解 Asyncio 框架的核心原理与应用实践。内容包括事件循环机制、协程任务调度、异步 IO 处理以及并发任务管理策略。通过构建高并发网络请求与异步数据处理案例,帮助开发者掌握 Python 在高并发场景中的高效开发方法,并提升系统资源利用率与整体运行性能。

117

2026.03.12

C# ASP.NET Core微服务架构与API网关实践
C# ASP.NET Core微服务架构与API网关实践

本专题围绕 C# 在现代后端架构中的微服务实践展开,系统讲解基于 ASP.NET Core 构建可扩展服务体系的核心方法。内容涵盖服务拆分策略、RESTful API 设计、服务间通信、API 网关统一入口管理以及服务治理机制。通过真实项目案例,帮助开发者掌握构建高可用微服务系统的关键技术,提高系统的可扩展性与维护效率。

350

2026.03.11

Go高并发任务调度与Goroutine池化实践
Go高并发任务调度与Goroutine池化实践

本专题围绕 Go 语言在高并发任务处理场景中的实践展开,系统讲解 Goroutine 调度模型、Channel 通信机制以及并发控制策略。内容包括任务队列设计、Goroutine 池化管理、资源限制控制以及并发任务的性能优化方法。通过实际案例演示,帮助开发者构建稳定高效的 Go 并发任务处理系统,提高系统在高负载环境下的处理能力与稳定性。

63

2026.03.10

Kotlin Android模块化架构与组件化开发实践
Kotlin Android模块化架构与组件化开发实践

本专题围绕 Kotlin 在 Android 应用开发中的架构实践展开,重点讲解模块化设计与组件化开发的实现思路。内容包括项目模块拆分策略、公共组件封装、依赖管理优化、路由通信机制以及大型项目的工程化管理方法。通过真实项目案例分析,帮助开发者构建结构清晰、易扩展且维护成本低的 Android 应用架构体系,提升团队协作效率与项目迭代速度。

109

2026.03.09

JavaScript浏览器渲染机制与前端性能优化实践
JavaScript浏览器渲染机制与前端性能优化实践

本专题围绕 JavaScript 在浏览器中的执行与渲染机制展开,系统讲解 DOM 构建、CSSOM 解析、重排与重绘原理,以及关键渲染路径优化方法。内容涵盖事件循环机制、异步任务调度、资源加载优化、代码拆分与懒加载等性能优化策略。通过真实前端项目案例,帮助开发者理解浏览器底层工作原理,并掌握提升网页加载速度与交互体验的实用技巧。

108

2026.03.06

Rust内存安全机制与所有权模型深度实践
Rust内存安全机制与所有权模型深度实践

本专题围绕 Rust 语言核心特性展开,深入讲解所有权机制、借用规则、生命周期管理以及智能指针等关键概念。通过系统级开发案例,分析内存安全保障原理与零成本抽象优势,并结合并发场景讲解 Send 与 Sync 特性实现机制。帮助开发者真正理解 Rust 的设计哲学,掌握在高性能与安全性并重场景中的工程实践能力。

243

2026.03.05

PHP高性能API设计与Laravel服务架构实践
PHP高性能API设计与Laravel服务架构实践

本专题围绕 PHP 在现代 Web 后端开发中的高性能实践展开,重点讲解基于 Laravel 框架构建可扩展 API 服务的核心方法。内容涵盖路由与中间件机制、服务容器与依赖注入、接口版本管理、缓存策略设计以及队列异步处理方案。同时结合高并发场景,深入分析性能瓶颈定位与优化思路,帮助开发者构建稳定、高效、易维护的 PHP 后端服务体系。

684

2026.03.04

AI安装教程大全
AI安装教程大全

2026最全AI工具安装教程专题:包含各版本AI绘图、AI视频、智能办公软件的本地化部署手册。全篇零基础友好,附带最新模型下载地址、一键安装脚本及常见报错修复方案。每日更新,收藏这一篇就够了,让AI安装不再报错!

179

2026.03.04

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号