0

Sometimes when we use a plugin such as jQuery UI, it will add a class and overwrites existig styles. But I want to make sure my own class is always applied to the element.

.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");
});

By removing and adding class red, red goes after every other classes in generated source, and should overwrite the style defined in plugin_style. But the color is still blue.

Can someone explain this?

update

By adding !important may always keep .red applied. But without it, .red should also overwrites .plugin_style since it comes after.

4

1 に答える 1

3

スタイルはそれほどうまくいきません。これは特異性の問題であり、

「最後に定義されたルールは、以前の競合するルールよりも優先されます。」

ソース

plugin_style基本的に、これら 2つのスタイルを適用する順序に関係なくred最後に定義されたスタイルが優先されます。最後に定義したことがわかります。その結果、テキストが残るplugin_styleよりもスタイルが優先されます。redblue

順序を入れ替えると、赤が優先されます ( demo ):

.plugin_style {color: blue;}
.red {color: red;}
于 2013-04-08T04:05:59.457 に答える