我注意到如果我使用 jquery 更改元素的 css,它会删除一些已经指定给该元素的 css 规则。
例如,
.className, .className2, etc... {
background-color: black;
color : silver;
}
.className:hover, .className2:hover, etc... {
background-color: gray;
color : white;
}
现在,如果用户单击该元素,我希望它永久更改背景以显示它已被单击,如果单击了另一个同级元素,它将失去其 jQuery 设置的 css 规则并返回到原始的 css 指定规则(又名,它将失去其 rgba 背景,并且“悬停”规则将被添加回来)
highlightClicked : function (el) {
el.css({
"background-color" : "rgba(70, 70, 70, 0.7)",
"color" : "white"
});
$('#parentElement > span').each(function () {
$($(this)).not(el).css({
"background-color" : "rgba(70, 70, 70, 0.0)",
"color" : "gray"
});
});
},
但是 jquery .css 似乎删除了那些原始规则。
如何保存它们?
最佳答案
与其使用 .css()
更改元素样式,更有效的方法是添加/删除类:
HTML
//add a universal class to target with jquery, my example is .target
<div class="target className">className</div>
<div class="target className2">className2</div>
CSS
.active, .active:hover{ //don't add .active:hover if you want an actual hover state
background-color:red; //Whatever style you want
color: #FFF; //Whatever style you want
}
JQUERY
$(".target").click(function(){
$(this).addClass("active").siblings(".target").removeClass("active"); //will add the class to the clicked element and remove it from anyothers
});
或者如果你想改变单个元素的类,你可以像这样简单地使用.toggleClass()
:
$(".target").click(function(){
$(this).toggleClass("active");
});
关于jquery css change 删除了一些 css 文件规则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26458212/