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 = 'white';
tagName.style.backgroundColor = 'black';

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

var tagName = document.getElementById("pTag");
tagName.cssText = "color:white;backgroundColor:balck";

方法二:

使用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';

改变前: 

 改变后:

暂时就这些啦

猜你喜欢

转载自blog.csdn.net/line233/article/details/81585450