Javascript改变css样式的四种方法

了解一些JavaScript知识的童鞋应该知道,js是可以改变任意的htm标签l和css样式的,以下是js动态改变css样式的几种方法。

例:

HTML:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link href="style/css1.css" rel="stylesheet" id="href"/>
</head>
<body>
    <p class="change-before" id="pTag">设法改变css的样式</p>
    <script src="script/test.js" rel="stylesheet">
    </script>
</body>
</html>

CSS1:

/*css1.css*/
.change-before {
    color: yellow;
    background-color: red;
    width: 20%;
    margin: 0 auto;
    text-align: center;
}

.change-after {
    color: red;
    background-color: yellow;
    width: 20%;
    margin: 0 auto;
    text-align: center;
}

CSS2:

.change-before {
    color: red;
    background-color: yellow;
    width: 20%;
    margin: 0 auto;
    text-align: center;
}

JS:

方法一:

使用obj.style对象:

//     /*第一种,单独给每一个属性设定属性值*/
var tagName = document.getElementById("pTag");
tagName.style.color = 'red';
tagName.style.backgroundColor = 'yellow';

// /*第二种,使用cssText设定一组样式,避免页面reflow,提高页面性能*/

var tagName = document.getElementById("pTag");

/*需要注意的一点是,使用cssText,其属性名字与在css中一致,不是驼峰式命名,
例如background-color,而不是backgroundColor*/
tagName.style.cssText = "background-color:yellow;color:red;";

方法二:

使用js的setAttribute()方法更改class属性值:

该方法有两个参数

tagName.setAttribute('class','change-after');

方法三:

 更改css样式表文件:

var link = document.getElementById('href');
link.setAttribute('href','style/css2.css');

方法四:

通过赋值替换原来的class属性值:

tagName.className = 'change-after';

改变前: 

 改变后:

暂时就这些啦

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值