我正在寻找一个解决方案,在HTML中寻找所有的锚标签,并获得文本和相应的字体大小。
例如,我想找一个解决方案,在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>