小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
今天我们来复习如何使用JavaScript DOM来进行内联样式修改,CSS class的修改,以及获取元素的真实样式,获取元素的真实宽高等。
目录
element.stylewindow.getComputedStyle()element.classNameelement.classList
设置内联样式
我们使用元素 style 属性来操作元素的内联样式。
style属性返回CSS属性的CSSStyleDeclaration只读对象,例如要将元素的color设置为红色
element.style.color = 'red';
如果是包含-的CSS属性,比如 -webkit-text-stroke,我们可以使用[]来访问该属性
element.style.['-webkit-text-stock'] = 'unset';
下面的表格中展示了常用的CSS属性
| CSS | JavaScript |
|---|---|
| background | background |
| background-attachment | backgroundAttachment |
| background-color | backgroundColor |
| background-image | backgroundImage |
| background-position | backgroundPosition |
| background-repeat | backgroundRepeat |
| border | border |
| border-bottom | borderBottom |
| border-bottom-color | borderBottomColor |
| border-bottom-style | borderBottomStyle |
| border-bottom-width | borderBottomWidth |
| border-color | borderColor |
| border-left | borderLeft |
| border-left-color | borderLeftColor |
| border-left-style | borderLeftStyle |
| border-left-width | borderLeftWidth |
| border-right | borderRight |
| border-right-color | borderRightColor |
| border-right-style | borderRightStyle |
| border-right-width | borderRightWidth |
| border-style | borderStyle |
| border-top | borderTop |
| border-top-color | borderTopColor |
| border-top-style | borderTopStyle |
| border-top-width | borderTopWidth |
| border-width | borderWidth |
| clear | clear |
| clip | clip |
| color | color |
| cursor | cursor |
| display | display |
| filter | filter |
| float | cssFloat |
| font | font |
| font-family | fontFamily |
| font-size | fontSize |
| font-variant | fontVariant |
| font-weight | fontWeight |
| height | height |
| left | left |
| letter-spacing | letterSpacing |
| line-height | lineHeight |
| list-style | listStyle |
| list-style-image | listStyleImage |
| list-style-position | listStylePosition |
| list-style-type | listStyleType |
| margin | margin |
| margin-bottom | marginBottom |
| margin-left | marginLeft |
| margin-right | marginRight |
| margin-top | marginTop |
| overflow | overflow |
| padding | padding |
| padding-bottom | paddingBottom |
| padding-left | paddingLeft |
| padding-right | paddingRight |
| padding-top | paddingTop |
| page-break-after | pageBreakAfter |
| page-break-before | pageBreakBefore |
| position | position |
| stroke-dasharray | strokeDasharray |
| stroke-dashoffset | strokeDashoffset |
| stroke-width | strokeWidth |
| text-align | textAlign |
| text-decoration | textDecoration |
| text-indent | textIndent |
| text-transform | textTransform |
| top | top |
| vertical-align | verticalAlign |
| visibility | visibility |
| width | width |
| z-index | zIndex |
如果需要批量覆盖现有的内联样式,可以使用 cssText 属性
element.style.cssText = 'color:red; background-color:yellow';
或者也可以使用setAttribute()方法
element.setAttribute('style','color:red; background-color:yellow');
设置完成后,也可以单条修改CSS样式
element.style.color = 'blue';
如果不想覆盖掉现有的样式,也可以将新的CSS追加到原有样式的后面
element.style.cssText += 'color:red; background-color:yellow';
我们也可以封装一个公共函数,通过传入一个key-value的对象来给元素设置CSS样式
function css(e, styles) {
for (const property in styles)
e.style[property] = styles[property];
}
使用css()来设置样式
let content = document.querySelector('#content');
css(content, { background: 'yellow', border: 'solid 1px red'});
HTML示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Style Demo</title>
</head>
<body>
<p id="content">用JavaScript来设置样式</p>
<p id="css">用css()工具函数来设置样式</p>
<script>
// #1
let p = document.querySelector('#content');
p.style.color = 'red';
p.style.fontWeight = 'bold';
// #2
function css(e, styles) {
for (const property in styles)
e.style[property] = styles[property];
}
let pcss = document.querySelector('#css');
css(pcss, { background: 'yellow', border: 'solid 1px red'});
</script>
</body>
</html>
最终HTML展示
获取内联样式
理论上来说我们可以通过style属性来获取元素的内联样式,但在实践中并不常用,因为style并不会返回其他地方的规则,比如class类的样式等。
要获得元素的所有样式,要使用window.getComputedStyle() 方法。
getComputedStyle()
getComputedStyle() 是 window 对象的一个方法,它返回指定元素的样式对象。
语法:
let style = window.getComputedStyle(element [,pseudoElement]);
getComputedStyle() 接受两个参数:
element是指定要返回样式的元素。如果是其它节点类型,例如 Text 节点,方法将会报错。pseudoElement指定要匹配的伪元素。默认为null。
例如,我们想要获取悬停状态a标签的所有 CSS 属性的样式值,我们要将:hover参数传递给 getComputedStyle() 方法:
let link = document.querySelector('a');
let style = getComputedStyle(link,':hover');
console.log(style);
返回值
getComputedStyle() 方法返回一个样式对象,它是 CSSStyleDeclaration 对象的一个实例。
例子
1)基础使用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS getComputedStyle() Demo</title>
<style type="text/css">
.message {
background-color: #fff3d4;
border: solid 1px #f6b73c;
padding: 20px;
color: black;
}
</style>
</head>
<body>
<p class="message" style="color:red">
这是getComputedStyle() Demo!
</p>
<script>
let message = document.querySelector('.message');
let style = getComputedStyle(message);
console.log('color:', style.color);
console.log('background color:', style.backgroundColor);
// 输出:
// color: rgb(255, 0, 0)
// background color: rgb(255, 243, 212)
</script>
</body>
</html>
2)伪元素示例
下面使用getComputedStyle() 方法从伪元素中提取CSS样式
<html>
<head>
<title>JavaScript getComputedStyle() Demo</title>
<style>
body {
font: arial, sans-serif;
font-size: 1em;
line-height: 1.6;
}
p::first-letter {
font-size: 1.5em;
font-weight: normal
}
</style>
</head>
<body>
<p id='main'>伪元素getComputedStyle() Demo</p>
<script>
let p = document.getElementById('main');
let style = getComputedStyle(p, '::first-letter');
console.log(style.fontSize);
// 输出:24px
</script>
</body>
</html>
className
使用className 属性来操作元素的 CSS 类
<ul id="menu" class="vertical main">
<li>首页</li>
<li>服务</li>
<li>关于</li>
<li>联系我</li>
</ul>
<script>
let menu = document.querySelector('#menu');
console.log(menu.className);
// 输出:vertical main
</script>
要增加一个class,可以使用+=运算符来添加到现有的class中
element.className += newClassName;
要完全覆盖class,可以直接使用=运算符
element.className = "class1 class2";
获取元素的完整class
let classes = element.className;
当然元素还有另一个属性可以更好的去操作CSS 类,classList。
classList
classList用来操作元素的 CSS 类。
classList 是一个元素的只读属性,它返回 CSS 类的集合。
const classes = element.classList;
classList 是一个 DOMTokenList 对象,表示元素的 class 属性的内容。
尽管 classList 是只读的,但可以使用各种方法来操作它包含的类。
例子
1)获取元素的 CSS 类
<div id="content" class="main red">JavaScript classList</div>
<script>
let div = document.querySelector('#content');
for (let cssClass of div.classList) {
console.log(cssClass);
}
// 输出:
// main
// red
</script>
2)添加一个或者多个类
使用add()方法来添加新的类
let div = document.querySelector('#content');
div.classList.add('info');
添加多个类
let div = document.querySelector('#content');
div.classList.add('info','visible','block');
3)删除类
使用 remove()方法来删除类
let div = document.querySelector('#content');
div.classList.remove('visible');
和add()方法一样,也可以删除多个类
let div = document.querySelector('#content');
div.classList.remove('block','red');
4)替换类
替换现有的类使用replace()方法
let div = document.querySelector('#content');
div.classList.replace('info','warning');
5)判断类是否存在
使用contains()来判断指定类是否存在,如果存在返回true,反之为false。
let div = document.querySelector('#content');
div.classList.contains('warning'); // true
6)切换类
如果元素的类包含指定的类名,则 toggle() 方法将其删除。如果类不包含类名,toggle() 方法会将其添加到类列表中。
let div = document.querySelector('#content');
div.classList.toggle('visible');
获取元素的宽高
下图显示了包含具有内容、padding、border和margin的块元素的 CSS 盒模型:
要获取包含padding和border的元素的宽度和高度,使用元素的 offsetWidth 和 offsetHeight 属性:
let box = document.querySelector('.box');
let width = box.offsetWidth;
let height = box.offsetHeight;
下图展示了一个元素的 offsetWidth 和 offsetHeight
要获取包含padding但不包含border的元素的宽度和高度,使用 clientWidth 和 clientHeight 属性:
let box = document.querySelector('.box');
let width = box.clientWidth;
let height = box.clientHeight;
下图展示了一个元素的 clientWidth 和 clientHeight:
要获取元素的margin,要使用getComputedStyle() 方法
let box = document.querySelector('.box');
let style = getComputedStyle(box);
let marginLeft = parseInt(style.marginLeft);
let marginRight = parseInt(style.marginRight);
let marginTop = parseInt(style.marginTop);
let marginBottom = parseInt(style.marginBottom);
同样,要获取元素的边框宽度
let box = document.querySelector('.box');
let style = getComputedStyle(box);
let borderTopWidth = parseInt(style.borderTopWidth) || 0;
let borderLeftWidth = parseInt(style.borderLeftWidth) || 0;
let borderBottomWidth = parseInt(style.borderBottomWidth) || 0;
let borderRightWidth = parseInt(style.borderRightWidth) || 0;
要获取窗口的高度和宽度
let width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
let height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
总结
今天我们复习了通过JavaScript DOM来操作元素的内联样式,动态的对内联样式去增删改查,同样也分享了对CSS的class的增删改查操作,如何获取元素的样式,获取元素的宽高,margin和border等。
如果你想跟着我一起复习DOM知识,微信搜索【小帅的编程笔记】,每天更新