外部js文件问题中的jQuery addClass
这是我的密码:外部js文件问题中的jQuery addClass,jquery,css,Jquery,Css,这是我的密码: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <script src="scripts/jquery-1.10.1.js"></script> </head> <body> <link href="css/colorcss.css" rel
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="scripts/jquery-1.10.1.js"></script>
</head>
<body>
<link href="css/colorcss.css" rel="stylesheet" />
<script type="text/javascript" src="scripts/sample.js"></script>
<form id="form1" runat="server">
<div>
<input type="button" id="btnSample" value="click me" />
<label id="lblAll">All Toggle</label>
</div>
</form>
</body>
</html>
css:
问题是,上述代码不起作用。我正在尝试使用addClass,其中js是在一些外部js文件中编写的。同样的剧本,如果我把它放在身体下面,效果很好。我做错了什么吗?那是因为在dummy之后出现在css中的
.defaultColor
总是覆盖.dummy
应用的颜色,因为它出现在.defaultColor
之前。因此,如果您切换css规则的放置顺序,它应该可以正常工作。这只是Css特性的问题
查看此顺序,以便.dummy
如果存在,将成功覆盖.defaultColor
.defaultColor {
background-color: aliceblue;
}
.dummy {
background: yellow;
}
一些阅读关于css的特殊性
请首先应用此代码删除旧类 像这样
$("body").on("click", "#lblAll", function () {
$("#lblAll").removeClass("defaultColor").toggleClass("dummy");
});
是的,我认为您已经编写了两次代码,所以它首先执行两次代码,这是在脚本/sample.js中编写的 第二个在你的页面中。 从任何一侧删除代码都可以解决您的问题 小提琴
小提琴[1]。使用
!重要信息
在css类中.dummy
这样:
.dummy {
background: yellow !important; /*<---here*/
}
.defaultColor {
background-color: aliceblue;
}
.defaultColor {
background-color: aliceblue;
}
.dummy {
background: yellow;
}
请检查外部脚本是否正在加载。您应该将所有代码包装在文档中准备就绪。。。您只是扭曲了第一部分:)两个都工作了。。困惑的这是怎么发生的??我可以在任何地方编写css类,对吗?因为
.defaultColor
出现在dummy之后,它覆盖了.dummy
中定义的样式,它从不将其涂成黄色,所以如果发生这种情况,我们必须使用!重要信息
正如第一个示例中所建议的,如果将类添加到元素中,则会获得更高的优先级,否则请将类写在默认类下面。但我将它们放在外部css类中,对吗?外部css类,我可以在任何地方定义,对吗?像OOP概念?是的,但要理解样式是css类的优先级更高,这就是为什么我们必须在第二个选项中遵循这样的堆叠顺序,否则我们必须使用!重要信息
Also check if I wrote the code 2 times then what will happen
.dummy {
background: yellow !important; /*<---here*/
}
.defaultColor {
background-color: aliceblue;
}
.defaultColor {
background-color: aliceblue;
}
.dummy {
background: yellow;
}