问题:想要修改在一个特定的Web页面元素上添加或替换一个样式设置。
解决方案:通过元素的style属性来修改:
elem.style.backgroundColor = "red"
如果修改单个元素的一个或多个CSS属性,可以使用元素的setAttribute()方法
elem.setAttribute("style","background-color:red;color:white;border:1px solid red'
);
//或者将其预先设置的一个class属性设置给它
elem.setAttribute("class","stripe");
还可以创建一个属性节点来设置
var styleAttr = document.createAttribute("style");
styleAttr.nodeValue = "background-color:red";
someElement.setAttribute(style);
额外知识:访问一个已有的样式设置
var className = document.getElementById('img').getAttribute('class");
elem.setAttribute("class",className);
```
获取一个计算的CSS属性,该方式可以跨浏览器工作
var bkcolor = elem.currentStyle?elem.currentStyle[‘backgroundColor’]:
window.getComputedStyle(elem).getPropertyValue(“background-color”);
“`
对无序列表使用条纹主题
问题:想要让列表隔行换色
解决方案:
var lis = document.querySelectorAll('li:nth-child(2n+1)');
for(var i =0;i<lis.length;i++ ){
lis[i].setAttribute("style","background-color":#ffeeee");
}
或者
var lis = document.querySelectorAll('li:nth-child(odd)');
for(var i =0;i<lis.length;i++ ){
lis[i].setAttribute("style","background-color":#eeeeff");
}
或者
var parentElement = document.getElementById("thelist");
var lis = parentElement.getElementsByTagName("li");
for(var i =0;i<lis.length;i++){
if(i%2 ==0){
lis[i].setAttribute("style","background-color:#ffeeee");
}
}