如何使用.css()應用!important?

我在應用!important樣式時遇到麻煩。 我試過了: css

$("#elem").css("width", "100px !important");

什麼都不作 ; 不會應用任何寬度樣式。 有沒有一種相似jQuery的方式來應用這種樣式,而沒必要覆蓋cssText (這意味着我首先須要解析它,等等)? 正則表達式

編輯 :我應該補充一點,我有一個樣式表,具備!important樣式,我試圖用!important樣式內聯重寫,因此使用.width()之類的方法不起做用,由於它被個人外部!important樣式覆蓋。 app

此外,將覆蓋之前的值的值的計算 ,因此我不能簡單地建立另外一個外部風格。 ide


#1樓

David Thomas的答案描述了一種使用$('#elem').attr('style', …) ,但警告使用它會刪除style屬性中先前設置的樣式。 這是一種使用attr()而不出現問題的方法: spa

var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');

做爲功​​能: code

function addStyleAttribute($element, styleAttribute) {
    $element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
addStyleAttribute($('#elem'), 'width: 100px !important');

這是一個JS Bin演示element


#2樓

此解決方案不會覆蓋任何先前的樣式,而只是應用您須要的樣式: get

var heightStyle = "height: 500px !important";
if ($("foo").attr('style')) {
  $("foo").attr('style', heightStyle + $("foo").attr('style').replace(/^height: [-,!,0-9,a-z, A-Z, ]*;/,''));
else {
  $("foo").attr('style', heightStyle);
}

#3樓

咱們首先須要刪除之前的樣式。 我使用正則表達式將其刪除。 這是更改顏色的示例: io

var SetCssColorImportant = function (jDom, color) {
       var style = jDom.attr('style');
       style = style.replace(/color: .* !important;/g, '');
       jDom.css('cssText', 'color: ' + color + ' !important;' + style); }

#4樓

這是我遇到這個問題後所作的... function

var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');

#5樓

在頭部附加樣式的另外一種方法:

$('head').append('<style> #elm{width:150px !important} </style>');

這會將樣式附加到全部CSS文件以後,所以它將具備比其餘CSS文件更高的優先級並被應用。

相關文章
相關標籤/搜索