[javascript] .css ()를 사용하여 중요를 적용하는 방법은 무엇입니까?

스타일을 적용하는 데 문제가 !important있습니다. 난 노력 했어:

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

이것은 아무것도 하지 않는다 ; 너비 스타일이 적용되지 않습니다. 덮어 쓰지 않고 이러한 스타일을 적용하는 jQuery와 같은 방법이 cssText있습니까? (먼저 스타일 을 구문 분석해야한다는 의미입니다.)

편집 : 스타일 인라인 !important으로 재정의하려는 스타일 의 스타일 시트가 !important있으므로 .width()외부 !important스타일에 의해 재정의 되므로 사용 등이 작동하지 않습니다 .

또한 이전 값을 재정의하는 값 이 계산 되므로 다른 외부 스타일을 만들 수 없습니다.



답변

이 문제는 jQuery가 !important속성을 이해하지 못하기 때문에 발생 하며 규칙을 적용하지 못합니다.

이 문제를 해결하고 다음을 통해 규칙을 참조하여 규칙을 적용 할 수 있습니다 addClass().

.importantRule { width: 100px !important; }

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

또는 사용하여 attr():

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

후자의 접근 방식은 이전에 설정된 인라인 스타일 규칙을 설정 해제합니다. 주의해서 사용하십시오.

물론 @Nick Craver의 방법이 더 쉽고 현명하다는 좋은 주장이 있습니다.

위의 attr()접근 방식은 원래 style문자열 / 속성 을 유지하기 위해 약간 수정되었으며 주석에서 falko 가 제안한대로 수정되었습니다 .

$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });


답변

나는 진짜 해결책을 찾았다 고 생각한다. 새로운 기능으로 만들었습니다.

jQuery.style(name, value, priority);

당신은으로 값을 얻을하는 데 사용할 수 있습니다 .style('name')단지 같은 .css('name'),와의 CSSStyleDeclaration을 얻기 .style()도 설정 값을, 그리고 – 능력 ‘중요’로 우선 순위를 지정할 수 있습니다. 참조 .

데모

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'));

출력은 다음과 같습니다.

null
red
blue
important

함수

(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);

CSS 값을 읽고 설정하는 방법에 대한 예는 내용을 참조하십시오 . 내 문제는 !important다른 테마 CSS와의 충돌을 피하기 위해 CSS에서 너비를 이미 설정 했지만 jQuery에서 너비를 변경하면 style 속성에 추가되므로 영향을 미치지 않습니다.

적합성

이 기사setProperty 에서는 기능을 사용하여 우선 순위를 설정 하기 위해 IE 9+ 및 기타 모든 브라우저가 지원된다고 말합니다. IE 8을 사용해 보았지만 실패했기 때문에 내 기능에서 지원을 작성했습니다 (위 참조). setProperty를 사용하여 다른 모든 브라우저에서 작동하지만 <IE 9에서 작동하려면 사용자 정의 코드가 필요합니다.


답변

다음 .width()과 같이 직접 너비를 설정할 수 있습니다 .

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

주석 업데이트 :
이 옵션도 있지만 요소의 모든 CSS를 대체하므로 더 실용적인지 확실하지 않습니다.

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


답변

const elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');

참고 : Chrome을 사용하면 다음과 같은 오류가 반환 될 수 있습니다.

elem [0] .style.removeAttribute는 함수가 아닙니다

문제 해결 .removeProperty과 같은 기능 을 사용하도록 회선 변경elem[0].style.removeProperty('width');


답변

David Thomas의 답변 은을 사용하는 방법을 설명 $('#elem').attr('style', …)하지만이를 사용하면 style속성 에서 이전에 설정 한 스타일이 삭제된다고 경고 합니다. attr()그 문제없이 사용하는 방법은 다음과 같습니다 .

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

기능으로서 :

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

다음은 JS Bin 데모 입니다.


답변

다른 답변을 읽고 실험 한 후에 이것이 나에게 효과적입니다.

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

그러나 IE 8 이하에서는 작동하지 않습니다.


답변

당신은 이것을 할 수 있습니다 :

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

“cssText”를 속성 이름으로 사용하고 CSS에 값으로 추가 할 항목을 사용하십시오.