簡體   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