【问题标题】:Lookup HTML fragments with known CSS properties查找具有已知 CSS 属性的 HTML 片段
【发布时间】:2019-10-29 03:35:44
【问题描述】:

我正在寻找某种“反向 CSS 选择器”:给定一个 HTML 文档,如何查找具有特定格式的片段?例如,我想获取使用粗体文本 (font-weight: bold;) 的段列表。鉴于此文件:

<h1>example</h1>
<p>This is <b>an example</b> with <span style="font-weight: bold">formatting</span>.
</p>

然后段列表将包括(例如通过 XPath 选择器给出):

  • /h1[1]
  • /p[1]/b[1]
  • /p[1]/span[1]

【问题讨论】:

  • @Rob 当然不是!我认为可能有一些浏览器 API、编程库、算法等来进行查找。原来getComputedStyle 就是答案!
  • 我明白我误解了这个问题。

标签: javascript css css-selectors getcomputedstyle


【解决方案1】:

您可以使用javascript循环遍历DOM中的所有elements并检查每个elementfont-weight

window.getComputedStyle(myDOMElement).getPropertyValue('font-weight');

400 的字体粗细是正常的(在 CSS 中,font-weight: normalfont-weight: 400 是相同的)所以任何高于 400font-weight 都表示该元素是粗体的。

注意在 CSS 中,font-weight 通常是 400700900

一旦您确定了一个粗体的element,您就可以将一个标识class 应用到该element

工作示例:

const allDOMElements = document.querySelectorAll('*');

for (let i = 0; i < allDOMElements.length; i++) {

  let fontWeight = window.getComputedStyle(allDOMElements[i]).getPropertyValue('font-weight');

  if (fontWeight > 400) {

    allDOMElements[i].classList.add('is-bold');
  }
}
.is-bold {
  color: rgb(255, 0, 0);
}
<h1>Example</h1>
<p>This is <b>an example</b> with <span style="font-weight: bold">formatting</span>.
</p>

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 1970-01-01
    • 2020-12-17
    • 2014-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多