下面,当我把font-size
和font-family
组合成font
,然后用JS改 >new-style
类,font-style: italic;
行被忽略:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Chapter 9, Example 5</title>
<style>
#divAdvert {
font: 12pt Arial;
}
.new-style {
text-decoration: underline;
font-style: italic;
}
</style>
</head>
<body>
<div id="divAdvert">
Here is an advertisement. Why doesn't this italicize?
</div>
<br><button onclick="clickMeh();">Click Meh</button>
<script>
function clickMeh() {
var divAdvert = document.getElementById("divAdvert");
divAdvert.className = "new-style";
}
</script>
</body>
</html>
但是当我将它们分开时,该行按预期显示为斜体:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Chapter 9, Example 5</title>
<style>
#divAdvert {
font-size: 12pt;
font-family: Arial;
}
.new-style {
text-decoration: underline;
font-style: italic;
}
</style>
</head>
<body>
<div id="divAdvert">
Here is an advertisement.
</div>
<br><button onclick="clickMeh();">Click Meh</button>
<script>
function clickMeh() {
var divAdvert = document.getElementById("divAdvert");
divAdvert.className = "new-style";
}
</script>
</body>
</html>
为什么??????
更新:感谢 Evgeny 和 Michael 的投入,我设法通过在 .new-style
前面添加 #divAdvert
(在 CSS 中)使其正常工作我认为这是最正确的答案。这会保留 ID 并识别 new-style
类完全依赖于 ID 的事实。 Codepen here .
最佳答案
这是一个CSS specificity问题。 #divAdvert
上的font
将覆盖由具有较低特异性的规则定义的所有字体属性,并且类的特异性低于 id。您只需要为更改匹配或使用更高的特异性。
我要么将 #divAdvert
的样式设置为一个类作为选择器(我在下面所做的)并附加新类而不是覆盖它,或者您可以使用 #divAdvert.new- style
而不是选择器中的 .new-style
。一般来说,我尽量避免使用 ID 来设置样式,因为您会遇到这样的问题。
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>Chapter 9, Example 5</title>
<style>
.divAdvert {
font: 12pt Arial;
}
.new-style {
text-decoration: underline;
font-style: italic;
}
</style>
</head>
<body>
<div id="divAdvert" class="divAdvert">
Here is an advertisement. Why doesn't this italicize?
</div>
<br><button onclick="clickMeh();">Click Meh</button>
<script>
function clickMeh() {
var divAdvert = document.getElementById("divAdvert");
divAdvert.classList.add('new-style');
}
</script>
</body>
</html>
关于javascript - `font` 本身似乎使 `font-style` 不可更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44787011/