【问题标题】:How to get the font-size in JS of a child node from the parent node?如何从父节点获取子节点的JS字体大小?
【发布时间】:2020-07-20 21:45:27
【问题描述】:

我正在寻找一种在 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;
}

应该输出各自的字体大小。但是,使用这个solution

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

【问题讨论】:

  • 你只是抓取所有有 40px 字体大小的锚标签...
  • 您期望得到什么?我的意思是链接只有一个规则在你的 CSS 中设置字体大小。

标签: javascript html css


【解决方案1】:

您可以执行以下操作来获取子节点。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多