HTML5 换肤的三种方案
html5 方案 三种 换肤
2023-09-11 14:22:54 时间
换肤的三种方案
- 通过id获取link元素,修改href属性
- 使用css自定义变量来设置颜色
- rel=”alternate stylesheet”并且title属性必须存在(常规style不应该设置title),此事将作为备用样式表而在默认情况下disabled。可在js中修改disabled的值。document.querySelectorAll(“link[rel^=alternate]”)
测试代码
- index.html
<!doctype html>
<html>
<head>
<meta charset="utf8">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="" id="customStyle"/>
<link rel="alternate stylesheet" title="customStyle" href="css/red.css"/>
<link rel="alternate stylesheet" title="customStyle" href="css/green.css"/>
<link rel="alternate stylesheet" title="customStyle" href="css/blue.css"/>
<script>
console.log(navigator.userAgent);
var styleHrefArr = ["", "red.css", "green.css", "blue.css"];
var styleColorArr = ["white", "red", "green", "blue"];
var styleIndex = 0;
var way = 0;
function changeStyle(){
styleIndex = (styleIndex + 1) % styleColorArr.length;
switch(way) {
case 0:
var style = document.getElementById("customStyle");
style.setAttribute("href", "css/" + styleHrefArr[styleIndex]);
break;
case 1:
var style = document.getElementById("style");
document.documentElement.style.setProperty("--color", styleColorArr[styleIndex]);
break;
case 2:
var elems = document.querySelectorAll("link[rel^=alternate]");
elems.forEach(function(item, index) {
item.disabled = !((styleIndex-1) == index);
});
break;
}
}
</script>
</head>
<body>
<button onclick="changeStyle()"> hello</button>
</body>
</html>
- main.css
:root {
--color: black;
}
body {
background-color: var(--color);
}
注意点
以上方法切换主题,由于优先级问题,main.css不能是”行内”或”内嵌”的,只能是”外联”的。且main.css必须最先声明
相关文章
- 《HTML5 2D游戏编程核心技术》——第3章,第3.3节实现游戏主循环
- 【JavaScript】HTML5存储方案
- (近万字)一篇文章带你了解HTML5和CSS3开发基础与应用-适合前端面试必备
- 《HTML5开发手册》——1.2 这些新元素从何而来
- 《Windows 8 开发权威指南:HTML5 和JavaScript卷》——1.3 Microsoft Design新特性
- 《HTML5 开发实例大全》——1.21 在网页中突出显示某些文字
- 《iOS应用开发指南——使用HTML5、CSS3和JavaScript》——1.2 内容和情景就是一切
- 《超越平凡的Web设计——HTML5+CSS3专业应用之道 (iWeb会场抢先版)》——第7章 直击HTML5
- html5 canvas 头像上传
- html5脚本编程
- HTML5_嵌套移动APP端的H5页面meta标签
- html5 canvas类库 实例