javascript - 如何从父节点获取子节点的JS字体大小?
问题描述
我正在寻找一种解决方案来查找 HTML 中的所有锚标记并获取文本和相应的字体大小。
例如:
<a href="#">First test</a>
<a href="#"><h2> Second test</h2></a>
<a href="#"><p>Third Test</p></a>
使用 CSS:
a{
font-size: 40px;
}
h2{
font-size: 20px;
}
p{
font-size: 10px;
}
应该输出相应的字体大小。但是,使用此解决方案:
var a = document.getElementsByTagName('a');
for (var i= 0; i < a.length; ++i){
var style = window.getComputedStyle(a[i], null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
console.log(a[i].textContent + " | font-size:" + fontSize);
console.log("-----------");
}
我总是得到第一级字体大小:
"First test | font-size:40"
"-----------"
" Second test | font-size:40"
"-----------"
"Third Test | font-size:40"
"-----------"
检查jsfiddle
解决方案
您可以执行以下操作来获取子节点。
var a = document.getElementsByTagName('a');
for (var i = 0; i < a.length; i++) {
let node = a[i];
let children = node.childNodes;
for (child of children) {
if (child.nodeType === 1) {
node = child;
break;
}
}
var style = window.getComputedStyle(node, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
console.log(a[i].textContent + " | font-size:" + fontSize);
console.log("-----------");
}
a {
font-size: 40px;
}
h2 {
font-size: 20px;
}
p {
font-size: 10px;
}
<a href="#">First test</a>
<a href="#">
<h2> Second test</h2>
</a>
<a href="#">
<p>Third Test</p>
</a>
推荐阅读
- nginx - Nginx 允许特定的 ip4 地址
- c++ - 如何设置我的构造函数以使头部和尾部指向一个哨兵?(在 C++ 中的单链表中)
- perl - 如何直接取消引用存储在另一个哈希中的哈希引用?
- asp.net-mvc - 如何在同一个解决方案中使用 Web API?
- oop - 我应该为每个不同的构造函数创建类还是应该只为一个类创建两个构造函数?
- python-3.x - 从具有多个条件的 Pandas 数据帧执行计算
- replace - How to create list of files containing only filename in one set_fact task
- postgresql - 将 JSON.RawMessage 转换为 JSON
- hdl - HDL - PC.hdl 但从 x2 8 位寄存器开始
- html - 我应该使用哪个“href”值?