Jak aplikować!ważne użycie.css ()?

Mam problem z zastosowaniem stylu, który jest !important. Próbowałem:

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

To nie robinic ; nie stosuje się żadnego stylu szerokości. Czy istnieje jQuery-owski sposób na zastosowanie takiego stylu bez konieczności nadpisywania cssText (co oznaczałoby, że najpierw muszę go przeanalizować itp.)?

Edit : dodam, że mam arkusz stylów ze stylem !important, który próbuję nadpisać za pomocą stylu !important, więc używanie .width() i tym podobnych nie działa, ponieważ dostaje overridden by my external !important style.

Również wartość, która nadpisze poprzednią wartość jest obliczana , więc nie mogę po prostu stworzyć innego zewnętrznego stylu.

Author: miken32, 2010-04-17

30 answers

Myślę, że znalazłem prawdziwe rozwiązanie. Przerobiłem ją na nową funkcję:

jQuery.style(name, value, priority);

Możesz go użyć, aby uzyskać wartości z .style('name') tak jak .css('name'), uzyskać CSSStyleDeclaration z .style(), a także ustawić wartości - z możliwością określenia priorytetu jako 'ważny'. Zobacz to .

Demo

var div = $('someDiv');
console.log(div.style('color'));
div.style('color', 'red');
console.log(div.style('color'));
div.style('color', 'blue', 'important');
console.log(div.style('color'));
console.log(div.style().getPropertyPriority('color'));

Oto wyjście:

null
red
blue
important

Funkcja

(function($) {    
  if ($.fn.style) {
    return;
  }

  // Escape regex chars with \
  var escape = function(text) {
    return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  };

  // For those who need them (< IE 9), add support for CSS functions
  var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue;
  if (!isStyleFuncSupported) {
    CSSStyleDeclaration.prototype.getPropertyValue = function(a) {
      return this.getAttribute(a);
    };
    CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) {
      this.setAttribute(styleName, value);
      var priority = typeof priority != 'undefined' ? priority : '';
      if (priority != '') {
        // Add priority manually
        var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) +
            '(\\s*;)?', 'gmi');
        this.cssText =
            this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';');
      }
    };
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
      return this.removeAttribute(a);
    };
    CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) {
      var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?',
          'gmi');
      return rule.test(this.cssText) ? 'important' : '';
    }
  }

  // The style function
  $.fn.style = function(styleName, value, priority) {
    // DOM node
    var node = this.get(0);
    // Ensure we have a DOM node
    if (typeof node == 'undefined') {
      return this;
    }
    // CSSStyleDeclaration
    var style = this.get(0).style;
    // Getter/Setter
    if (typeof styleName != 'undefined') {
      if (typeof value != 'undefined') {
        // Set style property
        priority = typeof priority != 'undefined' ? priority : '';
        style.setProperty(styleName, value, priority);
        return this;
      } else {
        // Get style property
        return style.getPropertyValue(styleName);
      }
    } else {
      // Get CSSStyleDeclaration
      return style;
    }
  };
})(jQuery);

Zobacz to , aby uzyskać przykłady odczytu i ustawiania wartości CSS. Moim problemem było że już ustawiłem !important dla szerokości w moim CSS, aby uniknąć konfliktów z innymi motywami CSS, ale wszelkie zmiany wprowadzone do szerokości w jQuery nie będą miały wpływu, ponieważ zostaną dodane do atrybutu style.

Zgodność

Dla ustawienia z priorytetem przy użyciu funkcji setProperty, Ten artykuł mówi, że istnieje wsparcie dla IE 9+ i wszystkich innych przeglądarek. Próbowałem z IE 8 i nie udało się, dlatego zbudowałem wsparcie dla niego w moich funkcjach(patrz wyżej). Informatyka będzie działać na wszystkich innych przeglądarkach za pomocą setProperty, ale będzie potrzebował mojego niestandardowego kodu do pracy w

 296
Author: Aram Kocharyan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-06 18:59:24

Problem jest spowodowany tym, że jQuery nie rozumie atrybutu !important i jako taki nie stosuje reguły.

Możesz być w stanie obejść ten problem i zastosować regułę, odwołując się do niego, poprzez addClass():
.importantRule { width: 100px !important; }

$('#elem').addClass('importantRule');

Lub za pomocą attr():

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

To drugie podejście wyłączyłoby jednak wszelkie wcześniej ustawione reguły stylu in-line. Więc używaj ostrożnie.

Oczywiście jest dobry argument, że metoda @ Nick Craver jest łatwiejsza/mądrzejsza.

Powyższe, attr() podejście nieco zmodyfikowane, aby zachować oryginalny style string / properties:

$('#elem').attr('style', function(i,s) { return s + 'width: 100px !important;' });
 526
Author: David Thomas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-12 15:15:31

Możesz ustawić szerokość bezpośrednio za pomocą .width() Tak:

$("#elem").width(100);

Aktualizacja dla komentarzy: Masz również tę opcję, ale zastąpi ona wszystkie css na elemencie, więc nie wiem, czy jest bardziej opłacalna:

$('#elem').css('cssText', 'width: 100px !important');
 136
Author: Nick Craver,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-04-16 21:22:50
var elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');
 65
Author: BettaSplendens,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-13 18:18:29

Odpowiedź Davida Thomasa opisuje sposób użycia $('#elem').attr('style', …), ale ostrzega, że użycie jej spowoduje usunięcie wcześniej ustawionych stylów w atrybucie style. Oto sposób użycia attr() bez tego problemu:

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

Jako funkcja:

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

Oto js bin demo .

 51
Author: Rory O'Kane,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:26:34

Po przeczytaniu innych odpowiedzi i eksperymentowaniu, to działa na mnie:

$(".selector")[0].style.setProperty( 'style', 'value', 'important' );

To nie działa w IE 8 i pod, choć.

 27
Author: Nate,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-02 23:33:39

Możesz to zrobić:

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

Używanie" cssText " jako nazwy właściwości i cokolwiek chcesz dodać do CSS jako jego wartość.

 22
Author: hawkeye126,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:31:09

Można to osiągnąć na dwa sposoby:

$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
 17
Author: kva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-05 04:11:49

Nie ma potrzeby przechodzenia do złożoności odpowiedzi @AramKocharyan, ani potrzeby dynamicznego wstawiania znaczników stylów.

Po prostu Nadpisz styl, ale nie musisz niczego analizować, dlaczego?

// Accepts the hyphenated versions (i.e. not 'cssFloat')
function addStyle(element, property, value, important) {
    // Remove previously defined property
    if (element.style.setProperty)
        element.style.setProperty(property, '');
    else
        element.style.setAttribute(property, '');

    // Insert the new style with all the old rules
    element.setAttribute('style', element.style.cssText +
        property + ':' + value + ((important) ? ' !important' : '') + ';');
}

Nie można użyć removeProperty(), ponieważ nie usunie reguł !important w Chrome.
Nie można używać element.style[property] = '', ponieważ akceptuje tylko camelCase w Firefoksie.

Prawdopodobnie możesz to skrócić za pomocą jQuery, ale ta funkcja vanilla będzie działać na nowoczesne przeglądarki, Internet Explorer 8 itp.

 14
Author: Hashbrown,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:30:07

Oto, co zrobiłem po napotkaniu tego problemu...

var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
 12
Author: kebyang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:27:15

To rozwiązanie nie nadpisuje żadnego z poprzednich stylów, po prostu stosuje ten, którego potrzebujesz:

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);
}
 9
Author: Alain Beauvois,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-05 13:44:39

Jeśli nie jest to tak istotne, a ponieważ masz do czynienia z jednym elementem, który jest #elem, możesz zmienić jego id na coś innego i styl go jak chcesz...

$('#elem').attr('id', 'cheaterId');

I w CSS:

#cheaterId { width: 100px;}
 9
Author: Sinan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:25:11

Najprostszym i najlepszym rozwiązaniem tego problemu było po prostu użycie addClass() zamiast .css () lub .attr ().

Na przykład:

$('#elem').addClass('importantClass');

I w pliku CSS:

.importantClass {
    width: 100px !important;
}
 9
Author: Jack Fairfield,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:32:31

Zamiast używać funkcji css() spróbuj użyć funkcji addClass():

  <script>
  $(document).ready(function() {
    $("#example").addClass("exampleClass");
  });
  </script>

  <style>
  .exampleClass{
    width:100% !important;
    height:100% !important;
  }
  </style>
 8
Author: user3778043,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-11-24 09:15:05

FYI, to nie działa, ponieważ jQuery go nie obsługuje. Został złożony mandat na 2012 (#11173 $(elem).css ("property", " value !ważne") fails ), który został ostatecznie zamknięty jako WONTFIX.

 6
Author: Álvaro González,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-16 15:59:40

Najpierw musimy usunąć poprzedni styl. Usuwam go za pomocą wyrażenia regularnego. Oto przykład zmiany koloru:

var SetCssColorImportant = function (jDom, color) {
       var style = jDom.attr('style');
       style = style.replace(/color: .* !important;/g, '');
       jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
 6
Author: Rodrigo Perez Burgues,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:26:17

Alternatywny sposób dodawania stylu w głowie:

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

To dodaje styl po wszystkich plikach CSS, więc będzie miał wyższy priorytet niż inne pliki CSS i zostanie zastosowany.

 6
Author: h0mayun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:27:48

Może to wyglądać tak:

Cache

var node = $('.selector')[0];
OR
var node = document.querySelector('.selector');

Set CSS

node.style.setProperty('width', '100px', 'important');

Usuń CSS

node.style.removeProperty('width');
OR
node.style.width = '';
 6
Author: SerzN1,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:31:57

Zakładam, że próbowałeś bez dodawania !important?

Inline CSS (czyli jak JavaScript dodaje styl) nadpisuje arkusz stylów CSS. Jestem prawie pewien, że tak jest nawet wtedy, gdy reguła CSS arkusza stylów mA !important.

Kolejne pytanie (może głupie pytanie, ale trzeba je zadać.): Czy element, na którym próbujesz pracować display:block; Czy display:inline-block;?

Nie znając swojej wiedzy w CSS... elementy wbudowane nie zawsze zachowują się tak, jak można by się tego spodziewać.

 4
Author: Dave Gregory,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:24:18

Zrób to tak:

$("#elem").get(0).style.width= "100px!important";
 4
Author: user217447,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:28:23

Może to być odpowiednie dla twojej sytuacji, ale możesz używać selektorów CSS w wielu tego typu sytuacjach.

Jeśli, na przykład, chciałeś 3 .i 6. instancji.cssText aby mieć inną szerokość można napisać:

.cssText:nth-of-type(3), .cssText:nth-of-type(6) {width:100px !important;}

Lub:

.container:nth-of-type(3).cssText, .container:nth-of-type(6).cssText {width:100px !important;}
 3
Author: Tim Cutting,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-30 12:35:57

Myślę, że działa OK i może nadpisać każdy inny CSS przed (ten: element DOM):

this.setAttribute('style', 'padding:2px !important');
 3
Author: nobjta_9x_tq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:39:44

Odkryłem również, że niektóre elementy lub dodatki (jak Bootstrap) mają specjalne przypadki klas, w których nie grają dobrze z !important lub innymi wokół pracy, takimi jak .addClass/.removeClass, a więc musisz je włączyć/wyłączyć.

Na przykład, jeśli używasz czegoś takiego jak <table class="table-hover">, jedynym sposobem na pomyślną modyfikację elementów, takich jak kolory wierszy, jest włączenie / wyłączenie klasy table-hover, Jak to

$(your_element).closest("table").toggleClass("table-hover");

Mam nadzieję, że to obejście będzie pomocne dla kogoś! :)

 2
Author: Austin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-06-02 20:31:13

Możemy użyć setProperty lub cssText aby dodać !important do elementu DOM używając JavaScript.

Przykład 1:

elem.style.setProperty ("color", "green", "important");

Przykład 2:

elem.style.cssText='color: red !important;'
 2
Author: VISHNU Radhakrishnan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:33:41

Miałem ten sam problem próbując zmienić kolor tekstu elementu menu podczas "event". Najlepszy sposób, jaki znalazłem, gdy miałem ten sam problem, to:

Pierwszy krok: Utwórz w CSS nową klasę w tym celu, na przykład:

.colorw{ color: white !important;}

Ostatni krok: zastosuj tę klasę używając metody addClass w następujący sposób:

$('.menu-item>a').addClass('colorw');
Problem rozwiązany.
 2
Author: JoelBonetR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:34:37

Trzy przykłady pracy

Miałem podobną sytuację, ale korzystałem .find() po zmaganiach z .closer () przez długi czas z wieloma odmianami.

Przykładowy Kod

// Allows contain functions to work, ignores case sensitivity

jQuery.expr[':'].contains = function(obj, index, meta, stack) {
    result = false;
    theList = meta[3].split("','");
    var contents = (obj.textContent || obj.innerText || jQuery(obj).text() || '')
    for (x=0; x<theList.length; x++) {
        if (contents.toLowerCase().indexOf(theList[x].toLowerCase()) >= 0) {
            return true;
        }
    }
    return false;
};

$(document).ready(function() {
    var refreshId = setInterval( function() {
        $("#out:contains('foo', 'test456')").find(".inner").css('width', '50px', 'important');
    }, 1000); // Rescans every 1000 ms
});

Alternatywa

$('.inner').each(function () {
    this.style.setProperty('height', '50px', 'important');
});

$('#out').find('.inner').css({ 'height': '50px'});

Praca: http://jsfiddle.net/fx4mbp6c/

 2
Author: computerguy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:38:47

To rozwiązanie opuści cały obliczony javascript i doda ważny znacznik do elementu: Możesz to zrobić (np. jeśli chcesz ustawić szerokość z ważnym znacznikiem)

$('exampleDiv').css('width', '');
//This will remove the width of the item
var styles = $('exampleDiv').attr('style');
//This will contain all styles in your item
//ex: height:auto; display:block;
styles += 'width: 200px !important;'
//This will add the width to the previous styles
//ex: height:auto; display:block; width: 200px !important;
$('exampleDiv').attr('style', styles);
//This will add all previous styles to your item
 2
Author: Sebastian Leandro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-19 17:40:19

Https://jsfiddle.net/xk6Ut/256/

Alternatywnym podejściem jest dynamiczne tworzenie i aktualizowanie klas CSS w JavaScript. Aby to zrobić, możemy użyć elementu style i musimy użyć ID elementu style, abyśmy mogli zaktualizować klasę CSS

function writeStyles(styleName, cssText) {
    var styleElement = document.getElementById(styleName);
    if (styleElement) document.getElementsByTagName('head')[0].removeChild(
        styleElement);
    styleElement = document.createElement('style');
    styleElement.type = 'text/css';
    styleElement.id = styleName;
    styleElement.innerHTML = cssText;
    document.getElementsByTagName('head')[0].appendChild(styleElement);
}

...

  var cssText = '.testDIV{ height:' + height + 'px !important; }';
  writeStyles('styles_js', cssText)
 1
Author: Razan Paul,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-26 00:54:15

Najbezpieczniejszym obejściem jest dodanie klasy, a następnie wykonanie magii w CSS: -), addClass() i removeClass() powinny wykonać tę pracę.

 1
Author: Ryan S,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-29 09:40:05

Kolejna łatwa metoda rozwiązania problemu z dodaniem atrybutu style:

$('.selector').attr('style', 'width:500px !important');
 -6
Author: user3556813,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-21 15:41:01