设置元素的CSS样式属性

问题:想要修改在一个特定的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");
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值