gpt4 book ai didi

jquery - 如何确保类始终应用于 jQuery 的元素?

转载 作者:太空宇宙 更新时间:2023-11-04 00:02:53 24 4
gpt4 key购买 nike

有时候我们使用jQuery UI之类的插件时,它会添加一个类并覆盖现有的样式。但我想确保我自己的类始终应用于该元素。

.red {color: red;}
.plugin_style {color: blue;}
<p id="foo" class="red">foo</p>
<a href="#" id="doSomething">do something</a>
$.fn.doSomething = function() {
$(this).css("border", "1px solid #f00").addClass("plugin_style");
return $(this);
};

$("#doSomething").on("click", function() {
// this adds class "plugin_style"
// generated source: class="red plugin_style"
$("#foo").doSomething();

// remove "red"
// generated source: class="plugin_style"
$("#foo").removeClass("red");

// add "red"
// generated source: class="plugin_style red"
$("#foo").addClass("red");
});

通过删除和添加类 red,red 在生成的源代码中出现在所有其他类之后,并且应该覆盖 plugin_style 中定义的样式。但颜色仍然是蓝色。

谁能解释一下?

更新

通过添加 !important 可以始终保持 .red 应用。但是如果没有它,.red 也应该覆盖 .plugin_style 因为它在后面。

最佳答案

这种风格并不像那样工作。这是一个特异性问题,

"The last rule defined overrides any previous, conflicting rules."

source

Basically, no matter which order is used to apply these two styles, plugin_style or red, the last one defined is the one which will take precedence. You can see that you have defined plugin_style last, and as a result that style takes precedence over red causing the text to remain blue.

If you were to switch their order, then red would take precedence (demo):

.plugin_style {color: blue;}
.red {color: red;}

关于jquery - 如何确保类始终应用于 jQuery 的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15870935/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com