JavaScript-DOM-操作元素样式
这篇主要说一下如何用DOM操作元素样式。那先来看一下都有哪些属性或方法可以满足查看和修改元素样式。
表一:三种通用获取元素样式方式
方法/属性 | 描述 |
---|---|
style | 用法:元素.style.样式名,通过这种方式只能读取内联样式,无法读取样式表中的样式。可以通过:元素.style.样式名=样式值修改内联样式 |
currentStyle | 用法:元素.currentStyle.样式名,获取到当前样式,只读,只有IE支持 |
getComputedStyle() | 只读不可修改,有两个参数。第一个,获取样式的元素对象。第二个,传递一个伪元素,一般传null 。返回一个封装了当前元素样式的对象,不兼容IE8以下版本 |
表二:获取某一元素样式属性
属性 | 描述 |
---|---|
clientHeight | 返回包括内容区和内边距的高 |
clientWidth | 返回包括内容区和内边距的宽 |
offsetHeight | 返回包括内容区和内边距和边框的高 |
offsetWidth | 返回包括内容区和内边距和边框的宽 |
offsetParent | 返回离当前元素最近的开启了定位的父元素,也就是position不为static若所有祖先元素都未开启定位,则返回body |
offsetLeft | 返回相对于其父元素的水平偏移量 |
offsetTop | 返回相对于其父元素的垂直偏移量 |
scrollWidth | 返回整个滚动区域的宽 |
scrollHeight | 返回整个滚动区域的高 |
scrollLeft | 返回水平滚动条滚动距离 |
scrollTop | 返回垂直滚动条滚动距离 |
亲自试一试
以下例子包含了上面提到的所有方法及属性,不妨试一试。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DOM-操作元素样式示例</title>
<style>
.box1 {
width: 300px !important;
height: 300px;
padding: 10px;
border: 5px solid rgb(97, 143, 221);
}
.box2 {
position: relative;
width: 400px;
height: 400px;
background-color: aquamarine;
overflow: auto;
}
.box3 {
width: 450px;
height: 450px;
margin-left: 15px;
margin-top: 15px;
}
</style>
<script>
window.onload = function () {
let box1 = document.getElementsByClassName('box1')[0];
// 读取box1的样式
// 语法:元素.style.样式名,通过这种方式只能读取内联样式,无法读取样式表中的样式。
console.log("style属性读取样式:", box1.style.backgroundColor, box1.style.width);
// 修改box1的样式 语法:元素.style.样式名=样式值
box1.style.backgroundColor = '#f3be74';
// !important优先级最高,内联样式优先级大于样式表
box1.style.width = '200px';
// 读取box1当前样式,语法:元素.currentStyle.样式名,只读样式,只有IE支持
// console.log(box1.currentStyle.height, box1.currentStyle.width)
// getComputedStyle()window的获取当前元素方法,只读样式
let styles = getComputedStyle(box1, null);
console.log("getComputedStyle()方法读取样式", styles.height, styles.width)
// 其他查看元素样式属性,只读
console.log("包括内容区和内边距的宽、高:", box1.clientHeight, box1.clientWidth);
console.log("包括内容区和内边距和边框的宽、高:", box1.offsetHeight, box1.offsetWidth);
let box2 = document.getElementsByClassName('box2')[0];
let box3 = document.getElementsByClassName('box3')[0];
// 获取离当前元素最近的开启了定位的父元素
console.log("当前元素的定位父元素", box2.offsetParent, box3.offsetParent);
console.log("相对于其父元素的水平、垂直偏移量:", box3.offsetLeft, box3.offsetTop);
let btn = document.getElementsByTagName("button")[0];
/**
* 触底小实例
* */
btn.onclick = function () {
console.log("获取整个滚动区域的宽、高:", box2.scrollWidth, box2.scrollHeight);
console.log("获取水平、垂直滚动条滚动的距离:", box2.scrollLeft, box2.scrollTop);
// 滚动条触底判断-例子
if (box2.scrollHeight - box2.scrollTop == box2.clientHeight) {
alert("到底啦!")
}
}
}
</script>
</head>
<body>
<div class="box1" style="background-color: rgb(195, 227, 140);">
</div>
<div class="box2">
<div class="box3">
</div>
</div>
<button>查看相关样式</button>
</body>
</html>