JavaScript 如何获取特定元素的字体属性
给定一个字符串元素,任务是使用JavaScript获取特定元素的字体属性。
方法:
- 将字符串存储到变量中。
- 然后使用element.style.property来获取该元素的属性值。
示例1: 此示例获取元素[id=’GFG’]的字体系列。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get font properties of
particular element in JavaScript ?
</title>
</head>
<body style="text-align: center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3 id="GFG" style="font-family: sans-serif;">
How to get font properties of
particular element in JavaScript ?
</h3>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG_Res"></p>
<script>
let elm1 = document.getElementById("GFG");
let elm2 = document.getElementById("GFG_Res");
function GFG_Fun() {
elm2.innerHTML =
"Font-style Property: '"
+ elm1.style.fontFamily + "'";
}
</script>
</body>
</html>
输出:
示例2: 此示例获取元素[id = ‘GFG’]的字重。
<!DOCTYPE html>
<html lang="en">
<head>
<title>
How to get font properties of
particular element in JavaScript ?
</title>
</head>
<body style="text-align: center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<h3 id="GFG" style="font-weight: bold;">
How to get font properties of
particular element in JavaScript ?
</h3>
<button onclick="GFG_Fun()">
Click Here
</button>
<p id="GFG_Res"></p>
<script>
let elm1 = document.getElementById("GFG");
let elm2 = document.getElementById("GFG_Res");
function GFG_Fun() {
elm2.innerHTML =
"Font-weight Property: '"
+ elm1.style.fontWeight + "'";
}
</script>
</body>
</html>
输出: