2012-08-09 95 views
19

如果存在使用!important的CSS規則,是否有辦法刪除!important規則,以便我可以使用JS或jQuery進行更進一步的下游樣式更改?我可以使用jquery刪除/否定css!重要規則嗎?

theirs.css

div.stubborn { display: none !important; } 

mine.js

$('.stubborn').fadeIn(); // won't work because of !important flag 

不幸的是,我沒有在應用!important規則的風格控制,所以我需要一個解決。

回答

15

不幸的是,你不能沒有使用!important爲包括theirs.css下方內嵌/內部樣式覆蓋!important

您可以定義!important樣式並將其添加到.stubborn,然後調整不透明度。見下文,

CSS:

div.hidden_block_el { 
    display: block !important; 
    opacity: 0; 
} 

JS:

$('.stubborn') 
    .addClass('hidden_block_el') 
    .animate({opacity: 1}); 

DEMO:http://jsfiddle.net/jjWJT/1/

另一種方法(內置),

$('.stubborn') 
    .attr('style', 'display: block !important; opacity: 0;') 
    .animate({opacity: 1}); 

DEMO:http://jsfiddle.net/jjWJT/

+9

+1可悲的是,這是一個黑客之一的類型需要使用時,有在」重要的一個工作,爆炸「工廠 – 2012-08-09 19:57:45

+1

一些很好的閱讀http://stackoverflow.com/questions/3706819/what-are-the-implications-of-using-important-in-css http://coding.smashingmagazine.com/2010/11/02/the-important-css-declaration-how-and-when-to-use-it/ – 2012-08-09 20:03:50

+0

+1 I second _inline_ approach,尤其是在我使用jQuery Mobile的情況下。 – Omar 2013-04-09 16:49:45

0

您可以添加新的CSS樣式的重要補充它,會覆蓋原有的風格

這是從另一個答案在javascript:

function addNewStyle(newStyle) { 
var styleElement = document.getElementById('styles_js'); 
if (!styleElement) { 
    styleElement = document.createElement('style'); 
    styleElement.type = 'text/css'; 
    styleElement.id = 'styles_js'; 
    document.getElementsByTagName('head')[0].appendChild(styleElement); 
} 
styleElement.appendChild(document.createTextNode(newStyle)); 
} 

addNewStyle('td.EvenRow a {display:inline !important;}') 

這個答案是here

此外我相信你可以添加這樣的造型

 .css({ 'display' : 'block !important' }); 

in jQuery

1

您需要創建一個新的類來應用淡入淡出。

CSS:

div.stubborn { display: none !important; } 
div.stubborn.fade-ready { display: block !important; opacity: 0; } 

JS:

$('.stubborn').addClass('fade-ready').animate({opacity: 1}); //to show 
$('.stubborn').fadeOut(function() {$(this).removeClass('fade-ready');}); //to hide 

DEMO HERE

3

只是style=""標記添加到任何圖像這個問題,希望他們都有某種定義類向他們表示,這是容易做到的。

$('div.stubborn').attr('style', 'display: inline !important;');​ 

jsFiddle DEMO

0

我嘗試了好幾種方法,但我已通過添加CSS樣式在一個單獨的類來得到最好的結果,然後使用jQuery刪除(重要!):

CSS :

.important-css-here { display: block !important;} 

在jQuery中:

$("#selector").addClass("important-css-here"); 

然後,當我需要:

$("#selector").removeClass("important-css-here"); 

就像一個魅力;-)