如何使用JQuery添加/更新css类。
我知道可以使用这个使用JQuery添加css规则来向DOM元素添加css,但我想要添加/删除css类本身。
你不能直接使用jQuery更新单独CSS文件中的CSS类。但是,你可以创建一个<style>
标签,并添加/覆盖CSS类:
$('<style>.newClass { color: red; }</style>').appendTo('body');
当更新CSS类时,您需要注意层叠顺序。否则,可能不会得到您想要的效果。
使用最新版本的Jquery太容易了,只需像这样:
$('jQuery selector').css({"css property name":"css property value"});
例如:$('#MyDiv').css({"background-color":"red"});
$("#UniqueName").remove();
$("<style id="UniqueName" type='text/css'> .MyClass{ color:#f00 !important; font-weight:bold !important;} </style>").appendTo("head");
最好使用逻辑小类,并使用jQuery的.toggleClass()
方法。
.Bold{ font-weight:bold; }
.Italic {font-style:italic;}
function SwitchFont(){
$(".MyObjects").toggleClass("Bold");
$(".MyObjects").toggleClass("Italic");
}
When I write down this code to easily understand
Code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#btn1").click(function(){
$("h1,p").toggleClass("blue");
$("div").toggleClass("important");
});
});
</script>
<style>
.important {
font-weight: bold;
font-size: 40px;
color: chartreuse;
}
.blue{
color: #000080;
}
</style>
</head>
<body>
<h1>This is example</h1>
<p>This is example</p>
<div>Some important message </div>
<button id="btn1">Add class </button>
</body>
</html>
$("#button1").click(function(){
$(#the_div).addClass('myClass');
});
$("#button2").click(function(){
$("#the_div").removeClass('myClass');
});
http://api.jquery.com/addClass/
这将向DOM元素添加属性。
如果您想覆盖现有属性,请使用jQuery .css,在您的情况下进行更新。
.css 会作为内联样式添加,因此所有类属性都将被覆盖。
$("#tagid").addClass('classname');
。否则,您可以使用类似$("#tagid").css("color","red");
的方式。请参阅 .css。 - Zach L