首页 > 解决方案 > 看起来我的 javascript 中断了我的 css

问题描述

我正在做一些小的网络项目

  1. 我使用 javascript 来更改颜色 - 看起来不错
  2. 我在 mousehove ( :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>

标签: javascriptjqueryhtmlcss

解决方案


那是因为内联样式比通过类进行样式设置具有更高的优先级。当您通过JQueryusing添加样式时.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>


推荐阅读