好玩的.css样式表&变量+换肤

集合:可通过索引获取对应的元素

rule:规则,样式表由规则组成,规则由属性组成

## document.styleSheets,所有样式表(<style>、<link>)的集合

## document.styleSheets[0].cssRules,当前样式表下,所有rule的集合,有个索引的概念

const styleSheet = document.createElement('style');
styleSheet.innerHTML = `
.rule0 {

}

.rule1 {
  /* 通过 cssRules[1] 获取 */
}

.hello-bar {
  /* 我是rule2 */
}

.rrrred {
color:red!important;
}
`;
document.body.appendChild(styleSheet); 
// 这里没有插入head...是为了保证是最后一个样式表(有时候人们会把<style>写在任何地方)

// 接下来测试用
const styleManage = document.styleSheets[document.styleSheets.length - 1];

## 控制样式表rule(我发现操作之后不会反应到<style>内)

- 插入 insertRule()

styleManage.insertRule('.newRule {color:red!important;}',0); // 让它成为第0条
console.log(styleManage.cssRules);

// .newRule已经生效了

- 删除 deleteRule(index)

// 删除.rrrred,因为之前插入了一条规则,现在它的index变为 4 了
styleManage.deleteRule(4);
console.log(styleManage.cssRules);

// .rrrred已经失效了,即使是删除,<style>内的.rrrred依然存在

- addRule()、removeRule()是IE的方法,推荐使用上面的2个标准方法 

- rules、cssRules,rules应该是IE的,因为 styleManage.cssRules === styleManage.rules; // true,不排除IE下有特殊表现

 ## style控制

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>dynamic-skins</title>
    <style>
        :root {
            /*测试:root*/
            --primary: #383680;
        }

        body {
            /*--primary: yellow;*/
        }

        button {
            outline-color: transparent;
            border: none;
            border-radius: 4px;
            font-size: 10px;
        }

        button[primary] {
            background-color: var(--primary);
            color: #fff;
            padding: 6px 12px;
        }

        button[primary]:focus {
            outline-color: #333;
        }

        .cube {
            --primary: red;
            color: var(--primary);
        }
    </style>
</head>
<body>
<button primary>编辑</button>
<input type="color" onchange="setSkin(event)">
<div class="cube">
    CUBE
</div>
<script>
	function setSkin(evt) {
		const color = evt.target.value;

		// 注意:root对应的是document.documentElement
		// body里的变量,要用document.body,因为会override
		const styleManage = document.documentElement.style;

		if (!styleManage.getPropertyValue('--primary')) {
			console.log('获取不到在:root设置的变量,只有setProperty()之后才能获取');
		}
		styleManage.setProperty('--primary', color);
		console.log(styleManage.getPropertyValue('--primary'));
	}

</script>
</body>
</html>

 

- :root是document.documentElement(即<html>)

- 存在作用域,会出现override问题

- 跨作用域访问,还没找到。。

- 其他方法

## 资源

- 样式表:https://developer.mozilla.org/zh-CN/docs/Web/API/Document/styleSheets

- rule:https://developer.mozilla.org/zh-CN/docs/Web/API/CSSStyleSheet

- rule属性:http://www.runoob.com/jsref/obj-cssstyledeclaration.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值