`font`本身似乎使`font-style`不可更改

时间:2017-06-27 18:03:19

标签: javascript css

在下文中,当我将font-sizefont-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>

Codepen here

但是当我将它们分开时,这条线按预期斜体显示:

<!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>

Codepen here

为什么???????

更新:感谢Evgeny和Michael的意见,我设法通过在#divAdvert(在CSS中)添加.new-style来实现它,我认为这是最正确的答案。这会保留ID并识别new-style类完全依赖于ID的事实。 Codepen here

2 个答案:

答案 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高于fontfont-style: italic !important;本身包含其所有子属性,所以即使您不写它们,它们也是只是作为默认值。

您还可以在.class

中使用xvals = {1, 2} yvals = {3, 4} {Sequence @@ #, f @@ #} & /@ Tuples[{xvals, yvals}]