看来我的JavaScript中断了我的CSS

时间:2019-04-18 13:58:34

标签: javascript jquery html css

我正在从事一些小型Web项目

  1. 我使用javascript更改颜色-看起来不错
  2. 当鼠标悬停(:hover)时,我使用CSS来更改颜色-也很好

但是当我将其放在一起时,看起来只有javascript可以工作

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").css("color", "red");
  });
});
</script>
<style>
#text:hover {
color: blue;
}
</style>
</head>
<body>

<button>Set the color property of all p elements</button>

<p id="text">This is a paragraph.</p>
<p id="text">This is another paragraph.</p>

</body>
</html>

2 个答案:

答案 0 :(得分:3)

这是因为内联样式的优先级高于通过类的样式。当您使用JQuery通过.css()添加样式时,该样式将作为嵌入式样式应用。这比通过类申请具有更高的优先级。只需检查,您就会看到。

您应该做的是

$("button").click(function(){
    $("p").addClass('custom-class');
  });

并将样式写为

.custom-class{
  color:red;
}

我已经对此进行了测试,并且正在工作。

.custom-class {
  color: red;
}
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").addClass('custom-class');
  });
});
</script>
<style>
#text:hover {
color: blue;
}
</style>
</head>
<body>

<button>Set the color property of all p elements</button>

<p id="text">This is a paragraph.</p>
<p id="text">This is another paragraph.</p>

</body>
</html>

答案 1 :(得分:1)

由于JS代码将添加比CSS优先级高的内联样式,因此可以改用如下类:

<!DOCTYPE html>
<html>

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("button").click(function() {
        $("p").addClass('red');
      });
      $("p").hover(function() {
        $(this).toggleClass('hover');
      });
    });
  </script>
  <style>
    #text.hover {
      color: blue;
    }
    .red {
      color: red;
    }
  </style>
</head>

<body>

  <button>Set the color property of all p elements</button>

  <p id="text">This is a paragraph.</p>
  <p id="text">This is another paragraph.</p>

</body>

</html>