CSS—根据字体大小选择元素,并动态地将样式应用于该文本

CSS - Selecting elements based on font-size and dynamically applying styles to that text

本文关键字:动态 样式 文本 应用于 元素 字体 选择 CSS      更新时间:2023-09-26

是否有办法在JavaScript 中根据font-size选择元素?

我想在JavaScript中根据每个元素的字体大小动态应用不同的样式(如font-weight和letter-spacing)。

我们可以选择所有的p标签并为它们应用样式。

p {
  color: green;
}

我想知道我是否可以做这样的事情(或那种效果;我知道下面的颜色不行):

font-size:14px {
  /* All font that is size 14px is now red*/
  color: red;
}
font-size:16px {
  /* All font that is size 16px is now blue*/
  color: blue;
}

样式可以从javascript:

document.getElementById("[id]").style.[css rule] = [value];

元素的style属性通过:

window.getComputedStyle([element], null).getPropertyValue('[css rule]')

的例子:

var all = document.getElementsByTagName("p");
for (var i = 0, max = all.length; i < max; i++) {
  if (window.getComputedStyle(all[i], null).getPropertyValue('font-size') > "15px") {
    all[i].style.fontWeight = "900";
  } else {
    all[i].style.fontWeight = "100";
  }
}
#myPara {
  font-size: 14px;
}
p+p {
  font-size: 18px;
}
<p id="myPara">This is some text.</p>
<p>This is some text.</p>
<p>This is some text.</p>

希望这对你有帮助。

$( "p" ).each(function() {
    if($(this).css('font-size')=='12px'){
        //Apply Styles
        $(this).css('color','red')
    }
})

JSFiddle