返回
DOM编程进阶--操纵CSS样式与获取真实样式
前端
2024-01-21 21:11:46
今天我们来复习如何使用JavaScript DOM来进行内联样式修改,CSS类的修改,以及获取元素的真实样式,获取元素的真实宽高等。
目录
- element.style
- window.getComputedStyle()
- classList
- Element.getBoundingClientRect()
element.style
JavaScript中的style属性允许我们直接访问并修改元素的内联样式。
<p id="demo">Hello World!</p>
我们可以使用JavaScript来修改该段落的字体大小:
document.getElementById("demo").style.fontSize = "20px";
我们还可以设置更多复杂的样式,比如设置背景色和边框:
document.getElementById("demo").style.backgroundColor = "lightblue";
document.getElementById("demo").style.border = "2px solid black";
window.getComputedStyle()
JavaScript中的getComputedStyle()方法允许我们获取元素的实际样式,包括继承的样式。
<p id="demo">Hello World!</p>
我们可以使用JavaScript来获取该段落的实际字体大小:
var fontSize = window.getComputedStyle(document.getElementById("demo")).fontSize;
getComputedStyle()方法也可以用于获取其他样式属性,比如背景色和边框:
var backgroundColor = window.getComputedStyle(document.getElementById("demo")).backgroundColor;
var border = window.getComputedStyle(document.getElementById("demo")).border;
classList
JavaScript中的classList属性允许我们操作元素的CSS类。
<p id="demo" class="important">Hello World!</p>
我们可以使用JavaScript来添加一个新的CSS类:
document.getElementById("demo").classList.add("urgent");
我们也可以删除一个现有的CSS类:
document.getElementById("demo").classList.remove("important");
Element.getBoundingClientRect()
JavaScript中的getBoundingClientRect()方法允许我们获取元素的真实宽高。
<p id="demo">Hello World!</p>
我们可以使用JavaScript来获取该段落的真实宽高:
var rect = document.getElementById("demo").getBoundingClientRect();
var width = rect.width;
var height = rect.height;
getBoundingClientRect()方法也可以用于获取元素相对于视口的坐标:
var rect = document.getElementById("demo").getBoundingClientRect();
var left = rect.left;
var top = rect.top;