- 切换body上的class
- 用js控制link标签的href属性链接,缺点是还得下载,不能完美切换
- 用js控制link标签元素的disabled属性,可以完美切换
<link rel="stylesheet" href="./css/default.css" title="默认">
<link rel="stylesheet alternate" href="./css/red.css" title="红色">
<link rel="stylesheet alternate" href="./css/green.css" title="绿色">
- 当link标签有title属性的时候,表示link标签可以通过js控制link元素的disabled属性来控制是否渲染link标签href链接的css
- 有title属性,如果link标签的rel属性值是"stylesheet alternate"的时候,默认是不渲染的,如果link标签的rel属性值是"stylesheet"的时候,没有"alternate",默认是渲染的
<div id="btnBox">
<button color="default">灰色</button>
<button color="red">红色</button>
<button color="green">绿色</button>
</div>
const btns=document.querySelectorAll("#btnBox button");
const arrBtn=Array.from(btns);
const links=document.querySelectorAll("link[title]");
const arrLink=Array.from(links);
arrBtn.forEach(btn=>{
btn.addEventListener("click",()=>{
arrLink.forEach(link=>{
//必须得先将link标签元素的disabled属性设置为true
link.disabled=true;
if(link.getAttribute("title")==btn.getAttribute("color")){
link.disabled=false;
}
});
});
});
需要注意的是每次点击按钮切换背景皮肤的时候需要将每个link元素的disabled属性值设置为true
参考文章:https://www.zhangxinxu.com/wordpress/2019/02/link-rel-alternate-website-skin/














网友评论