繁体   English   中英

使用 getComputedStyle 识别所有 P 标签的 CSS 字体粗细

[英]Use getComputedStyle to identify the CSS font-weight for all P tags

客观的

  • 要使用 getComputedStyle 来识别分配给页面中文本的 CSS 字体粗细,并将其作为文本记录到 P 标签/s 开头的跨度中。

原因

  • 创建一个供个人使用的书签,用于识别 CSS 用于在视觉上应用强/粗体文本的位置。 然后可以确定 CSS 是否应该替换为 HTML strong。

问题

  • 仅适用于页面中的第一个 P 标签。
  • 替换现有文本而不是添加到现有单词。

到目前为止的代码

var newClass = document.getElementsByTagName('p')
var length = newClass.length;
for (var i = 0; i < length; i++) {
  newClass[i].className =  newClass[i].className + "font--weight"
}

let pAll = document.querySelector('p.font--weight');
let calcStyles = window.getComputedStyle(pAll);
pAll.textContent = 'My computed font-weight is ' + calcStyles.getPropertyValue('font-weight');
pAll.innerHTML = '<span>' + pAll.textContent + '</span>'; 
  • 这可能吗,如果没有,问题就结束了。
  • 有没有更好的方法来实现这一目标?
  • JavaScript 不是 jQuery 中需要。

使用el.querySelectorAll()获取nodeListel.querySelector()将仅返回选择器的第一个节点。 然后你只需要使用getComputedStyle(selector).getPropertyValue('style')来获取计算的样式。 从那里只是将字符串连接在一起并将innerHTMLtextContent设置为字符串。

拥有nodeList后,通过循环运行元素以获取每个元素。

 let pTagClass = document.querySelectorAll('.check-weight') function getFontWeight(els) { els.forEach(weight => { // weight now represents each individual node in // our nodeList that was passed into the function let compStyle = getComputedStyle(weight).getPropertyValue('font-weight'); let str = `<span class="bookmark">font-weight is: ${compStyle},</span>` let currentText = weight.textContent weight.innerHTML = `${str} ${currentText}` }) } getFontWeight(pTagClass)
 .check-weight { font-family: "Bahnschrift", sans-serif; }.heavy { font-weight: bold; }.normal { font-weight: normal; }.light { font-weight: lighter; }.bookmark { font-weight: normal; font-size: smaller; background-color: yellow; padding: 2px; }
 <p class="heavy check-weight">This is a heavy weight</p> <p class="heavy check-weight">This is also a heavy weight</p> <p class="light check-weight">This is a light weight</p> <p class="normal check-weight">This is normal</p>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM