javascript - 看起来我的 javascript 中断了我的 css
问题描述
我正在做一些小的网络项目
- 我使用 javascript 来更改颜色 - 看起来不错
- 我在 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>
解决方案
那是因为内联样式比通过类进行样式设置具有更高的优先级。当您通过JQuery
using添加样式时.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>
推荐阅读
- kubernetes - CoreDNS 不使用 K8S / Minikube 解析命名空间外的服务 url
- c# - 如何在 C# 中保护静态 int
- sql - 在 oracle 中使用 listagg 时出错“STRING concatenation too long”
- .net - 如何通过 .NET Core 查找物理 CPU 核心数(不是逻辑 SMT 超线程)?
- oauth - oauth 范围是在什么级别定义的,在应用程序级别还是在用户级别?
- oracle - 如何在大型 CLOB 上使用 DISTINCT
- c++ - 如何在另一个类中使用带有构造函数的类?
- arrays - MongoDB.Driver.MongoWriteException:'写入操作导致错误。无法索引并行数组'
- python - 在 OpenCV 上输入更高分辨率的视频文件时 fps 低
- c++ - 为什么使用 for 和 while 循环在两个线程之间未解决锁定条件