前端研习录(前端研习录(29)——JavaScript CSS操作讲解及示例分析
版权声明
- 本文原创作者:清风不渡
- 博客地址:https://blog.csdn.net/WXKKang
重拾前端记忆,记录学习笔记,现在进入JavaScript CSS操作部分
一、HTML元素的style属性
通过使用网页元素节点的setAttribute方法直接操作网页元素的style属性,示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>清风不渡</title>
</head>
<body>
<div class="box" id="box1">Hello</div>
<script>
var box1 = document.getElementById("box1");
box1.setAttribute(
'style',
'height: 200px;'+'width: 200px;'
+'background-color: aqua;'+'border: 3px solid yellowgreen;'
);
</script>
</body>
</html>
执行结果如下:
二、元素节点的style属性
通过取得元素节点的style属性,再来设置样式,示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>清风不渡</title>
</head>
<body>
<div class="box" id="box1">Hello</div>
<script>
var box1 = document.getElementById("box1");
var box1Style = box1.style;
box1Style.height = "200px";
box1Style.width = "200px";
box1Style.backgroundColor = "green";
box1Style.border = "3px solid red";
</script>
</body>
</html>
结果如下:
三、cssText属性
也可以通过cssText属性来设置样式,示例如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>清风不渡</title>
</head>
<body>
<div class="box" id="box1">Hello</div>
<script>
var box1 = document.getElementById("box1");
var box1Style = box1.style;
box1Style.cssText =
'height: 200px;'+'width: 200px;'
+'background-color: aqua;'+'border: 3px solid yellowgreen;'
</script>
</body>
</html>
结果如下: