重拾前端记忆,记录学习笔记,现在进入JavaScript CSS操作部分
通过使用网页元素节点的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">Hellodiv>
<script>
var box1 = document.getElementById("box1");
box1.setAttribute(
'style',
'height: 200px;'+'width: 200px;'
+'background-color: aqua;'+'border: 3px solid yellowgreen;'
);
script>
body>
html>
执行结果如下:

通过取得元素节点的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">Hellodiv>
<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属性来设置样式,示例如下:
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">Hellodiv>
<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>
结果如下:
