使用js修改文档中的样式表

使用js修改文档中的样式表

大致总结为四步:

1. 先获取文档中所有的式样表,通过下标定位到得到你想要的样式表
var sheets = document.styleSheets;
	console.log(sheets);
var firstSheet = sheets[0];
2. 获取式样表中的规则列表
    (注:IE使用的是rules,其他的浏览器使用的是cssRules)
    通过下标定位到你想要的规则
var rules = firstSheet.cssRules || firstSheet.rules;
	var firstRule = rules[0];
这时候我们就可以看到这个规则里面的各种式样了
console.log(firstRule.selectorText);                //firstRules里面的选择器
console.log(firstRule.style.cssText);               //以字符串形式返回firstRules里面所有的css式样
console.log(firstRule.style.width);                 //获取某个样式的值
console.log(firstRule.style.height);
console.log(firstRule.style.backgroundColor);      
3.接下来,我们就可以对他们进行设置了
firstRule.style.width = '200px';
firstRule.style.height = '200px';
firstRule.style.backgroundColor = 'yellow';
4. 添加 ,删除rules
使用函数insertRule()函数插入,调用某一个sheet
 firstSheet.insertRule('body{background-color:green}',2);
  addRule('body','background-color:green',2)//但是IE不支持,需要使用addRule
使用position指定的规则删除  deleteRule(position)
firstSheet.deleteRule(2);
 //ie 不支持  removeRule(2)

还有一种稍微快速点的方法,快速命中sheet
使用sheet快速获取式样表,只对style和link元素有效,首先把你想获取的style或link设置一个id值
var styleElement = docment.getElementByID('mystyle');
那么.我们就可以得到这个样式表了,注IE使用的是styleSheet,其他浏览器使用的是sheet
	var sheet = styleElement.sheet || styleElement.styleSheet;
		var rules = sheet.cssRules || sheet.rules;
		var firstRule = rules[0];
		console.log(firstRule.selectorText);
		console.log(firstRule.style.cssText);
		console.log(firstRule.style.width);
		console.log(firstRule.style.height);
		console.log(firstRule.style.backgroundColor);
下面就可以设置样式了,具体同上







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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值