Jade Dungeon

HTML

动态切换CSS文件

Alternative Style Sheets

<link href="reset.css"   rel="stylesheet"           type="text/css">
<link href="default.css" rel="stylesheet"           type="text/css" title="Default Style">
<link href="fancy.css"   rel="alternate stylesheet" type="text/css" title="Fancy">
<link href="basic.css"   rel="alternate stylesheet" type="text/css" title="Basic">

所有样式表都可分为3类:

  • title属性,rel属性值仅仅是stylesheet<link>无论如何都会加载并渲染,如reset.css
  • title属性,rel属性值仅仅是stylesheet<link>作为默认样式CSS文件加载并渲染,如default.css
  • title属性,rel属性值同时包含alternate stylesheet<link>作为备选样式CSS文件加载,默认不渲染,如red.cssgreen.css

alternate意味备用,相当于是 css 预加载进来备用,所以不会有上面那种切换延时

通过linkdisabled属性可以设定哪些样式生效,哪些样式失效。

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>style sample</title>
		<link href="reset.css"   rel="stylesheet" type="text/css">
		<link href="default.css" rel="stylesheet" type="text/css" title="Default Style">
		<link href="red.css"     rel="alternate stylesheet" type="text/css" title="red">
		<link href="green.css"   rel="alternate stylesheet" type="text/css" title="green">	
	</head>
	<body>
		<div>
			<div class="box"> <p>文字颜色</p> </div>
			<p>
				选择样式:
				<input id="default" type="radio" name="skin" value="default.css" checked><label for="default">默认</label>
				<input id="red" type="radio" name="skin" value="red.css"><label for="red">红色</label>
				<input id="green" type="radio" name="skin" value="green.css"><label for="green">绿色</label>
			</p>
		</div>	
	</body>
	<script>
		var eleLinks = document.querySelectorAll('link[title]');
		var eleRadios = document.querySelectorAll('input[type="radio"]');
		eleRadios.forEach(function(radio) {
			radio.addEventListener('click', function () {
					var value = this.value;
					eleLinks.forEach(function (link) {
							link.disabled = true;
							if (link.getAttribute('href') == value) {
							link.disabled = false;
							}
							});
					});
		});
	</script>
</html>