jQuery 中的样式表切换器。
作为对“新手跟进”评论的回应,我将尝试使其更具指导性。
我在写作时用来测试的页面可以在here找到。
页面展示
您将希望在每个页面的<head> 中的<link> 标记中显示当前样式表。 <link> 标记需要一个 id 以便稍后在 JavaScript 中引用。比如:
<?php
// Somewhere in the server side code, $current_stylesheet is read from the user's
// "preferences" - most likely from a database / session object
$current_stylesheet = $user->stylesheet;
?>
<link href='<?php echo $current_stylesheet ?>' rel='stylesheet' type='text/css' id='stylelink' />
更改偏好
一旦您显示用户样式表,您需要一种方法来更改它。创建一个<form>,当用户更改样式表时将向服务器发送请求:
<form method="GET" id="style_form" >
<select name="stylesheet" id="styleswitch">
<option value="css1.css">Black & White</option>
<option value="css2.css" selected="selected">Shades of Grey</option>
</select>
<input value='save' type='submit' />
</form>
服务器端
现在,如果没有 jQuery,提交此表单应该在当前页面上获得(如果您愿意,可以将其更改为 POST)stylesheet={new stylesheet}。因此,在您的引导程序/站点范围的包含文件中的某处,您对其进行检查,这是一个 php 示例:
$styles = array(
'css1.css' => 'Black & White',
'css2.css' => 'Shades of Grey',
);
if (!empty($_GET["sytlesheet"]) {
// VALIDATE IT IS A VALID STYLESHEET - VERY IMPORTANT
// $styles is the array of styles:
if (array_key_exists($_GET["stylesheet"], $styles)) {
$user->stylesheet = $_GET["stylesheet"];
$user->save();
}
}
实时预览
此时,您已经为没有 javascript 的蹩脚的人提供了一个功能正常的样式切换器。现在你可以添加一些 jQuery 来让这一切更优雅地发生。您需要使用jQuery Form Plugin 来创建一个不错的ajaxForm() 函数,该函数将处理提交表单。在页面中添加 jQuery 和 jQuery Form 库:
<script type='text/javascript' src='/js/jquery.js'></script>
<script type='text/javascript' src='/js/jquery.form.js'></script>
现在我们已经包含了库 -
$(function() {
// When everything has loaded - this function will execute:
$("#style_form").ajaxForm(function() {
// the style form will be submitted using ajax, when it succeeds:
// this function is called:
$("#thediv").text('Now Using: '+$('#styleswitch').val());
});
$("#styleswitch").change(function() {
// When the styleswitch option changes, switch the style's href to preview
$("#stylelink").attr('href', $(this).val());
// We also want to submit the form to the server (will use our ajax)
$(this).closest('form').submit();
});
// now that you have made changing the select option submit the form,
// lets get rid of the submit button
$("#style_form input[type=submit]").remove();
});