在下文中,当我将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的意见,我设法通过在#divAdvert
(在CSS中)添加.new-style
来实现它,我认为这是最正确的答案。这会保留ID并识别new-style
类完全依赖于ID的事实。 Codepen here
答案 0 :(得分:3)
这是一个CSS specificity问题。 font
上的#divAdvert
将覆盖具有较低特异性的规则定义的所有字体属性,并且类的特异性低于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>
答案 1 :(得分:1)
因为#ID
层次结构中的.class
高于font
而font-style: italic !important;
本身包含其所有子属性,所以即使您不写它们,它们也是只是作为默认值。
您还可以在.class
xvals = {1, 2}
yvals = {3, 4}
{Sequence @@ #, f @@ #} & /@ Tuples[{xvals, yvals}]