通过名称获取样式的方法详解
发布时间:2023-12-28 01:31:09
获取样式的方法有多种,主要可以分为两种方式:内联样式和层叠样式。
1. 内联样式获取方法:
内联样式是直接在元素标签中定义的样式属性,可以通过元素节点的style属性来获取。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Style</title>
<style>
.red {
color: red;
}
.bold {
font-weight: bold;
}
</style>
</head>
<body>
<div id="example" class="red bold" style="font-size: 18px;">This is a sample text.</div>
<script>
var element = document.getElementById("example");
// 获取字体颜色
var color = element.style.color;
console.log("Color: " + color); // 输出:Color: red
// 获取字体大小
var fontSize = element.style.fontSize;
console.log("Font Size: " + fontSize); // 输出:Font Size: 18px
// 获取文字粗细
var fontWeight = element.style.fontWeight;
console.log("Font Weight: " + fontWeight); // 输出:Font Weight: bold
// 获取多个样式属性(使用CSSStyleDeclaration对象)
var styles = window.getComputedStyle(element);
console.log("Color: " + styles.color); // 输出:Color: rgb(255, 0, 0)
console.log("Font Size: " + styles.fontSize); // 输出:Font Size: 18px
console.log("Font Weight: " + styles.fontWeight); // 输出:Font Weight: bold
</script>
</body>
</html>
上述代码中,通过getElementById方法获取到id为“example”的元素,然后通过style属性获取到内联样式的属性值。通过window.getComputedStyle(element)方法可以获取到计算后的样式,返回的是一个CSSStyleDeclaration对象,可以通过对象的属性来获取样式值。
2. 层叠样式获取方法:
层叠样式是通过CSS文件或者<style>标签定义的样式属性,可以通过获取元素的属性值来获取。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Get Style</title>
<style>
#example {
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<div id="example">This is a sample text.</div>
<script>
var element = document.getElementById("example");
// 获取字体颜色
var color = getComputedStyle(element).color;
console.log("Color: " + color); // 输出:Color: rgb(255, 0, 0)
// 获取字体粗细
var fontWeight = getComputedStyle(element).fontWeight;
console.log("Font Weight: " + fontWeight); // 输出:Font Weight: bold
</script>
</body>
</html>
上述代码中,通过getElementById方法获取到id为“example”的元素,然后使用getComputedStyle(element)方法获取计算后的样式,并通过属性来获取样式值。
通过上述两种方式,可以获取到元素的样式值,进而进行操作。需要注意的是,使用style属性获取的是内联样式的值,使用getComputedStyle方法获取的是计算后的样式值。使用getComputedStyle方法可以获取到所有在样式表中定义的样式,包括内联样式和外部样式表的样式。
综上所述,通过名称获取样式的方法主要有两种:内联样式的获取使用元素节点的style属性,层叠样式的获取使用getComputedStyle方法。根据实际情况选择不同的方式获取样式值。
