복붙노트

[JQUERY] 신청 방법! .CSS를 사용하여 중요한 ()?

JQUERY

신청 방법! .CSS를 사용하여 중요한 ()?

해결법


  1. 1.문제는! 중요한 속성을 이해하지 jQuery를 발생하고, 같은 규칙을 적용하는 데 실패합니다.

    문제는! 중요한 속성을 이해하지 jQuery를 발생하고, 같은 규칙을 적용하는 데 실패합니다.

    당신은 addClass ()를 통해 그것을 참조하여 규칙을이 문제를 해결하려면 및 적용 할 수 있습니다 :

    .importantRule { width: 100px !important; }
    
    $('#elem').addClass('importantRule');
    

    또는 ATTR ()를 사용하여 :

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

    후자의 접근 방식은하지만, 이전에 설정 인라인 스타일 규칙 설정을 해제합니다. 그래서 신중하게 사용합니다.

    물론, @Nick Craver의 방법은 쉽게 / 현명하다는 좋은 인수가있다.

    약간 수정 위, ATTR () 접근 방식은 유지하기 위해 원래의 스타일 문자열 / 속성 및 코멘트에 팔코에 의해 제안 수정 :

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

  2. 2.나는 내가 진짜 해결책을 찾은 것 같아요. 나는 새로운 기능으로 만들었습니다 :

    나는 내가 진짜 해결책을 찾은 것 같아요. 나는 새로운 기능으로 만들었습니다 :

    jQuery.style (이름, 값, 우선 순위);

    당신은 단지 .CSS ( '이름')처럼 .style ( '이름')로 값을 얻을하는 데 사용할 수 있습니다, .style (), 또한 설정 값으로의 CSSStyleDeclaration을 얻을 - 같은 우선 순위를 지정하는 기능으로 '중요' . 이것 좀 봐.

    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 값을 설정하는 방법의 예는이를 참조하십시오. 내 문제는! 내가 이미 설정했다고 다른 테마 CSS를 피하기 충돌에 내 CSS의 폭 중요하지만,이 스타일의 속성을 추가 할 것이기 때문에 내가 jQuery를의 폭에 대한 변경 사항은 영향을받지 않을 것입니다.

    지정해 setProperty 기능을 사용하여 우선 순위 설정이 문서는 IE 9 이상 및 기타 모든 브라우저에 대한 지원이 말했다. 내가 IE 8 시도하고 내 기능에 대한 지원을 내장 이유입니다, 실패 (위 참조). 그것은 setProperty는을 사용하여 다른 모든 브라우저에서 작동하지만


  3. 3.직접 ()이 같은 .width 사용 폭을 설정할 수 있습니다 :

    직접 ()이 같은 .width 사용 폭을 설정할 수 있습니다 :

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

    덧글에 대한 업데이트 : 그래서 확실하지가 더 이상 실행 가능한, 당신은뿐만 아니라이 옵션을 가지고 있지만, 그것은 요소의 모든 CSS를 대체 ​​할 수 있습니다 :

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

  4. 4.

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

    노트 : 크롬과 같은 오류를 반환 할 수 있습니다 사용 :

    회선 변경하는 예에 ELEM 같이 .removeProperty 함수를 사용하여 [0] .style.removeProperty ( '폭'); 이 문제를 해결했습니다.


  5. 5.데이비드 토마스의 대답은 $ ( '#의 ELEM')를 사용하는 방법에 대해 설명합니다. ATTR ( '스타일', ...)하지만, 그것을 사용하는 스타일 속성에 이전에 설정된 스타일을 삭제된다는 경고합니다. 여기에 그 문제없이 ATTR ()를 사용하는 방법은 다음과 같습니다

    데이비드 토마스의 대답은 $ ( '#의 ELEM')를 사용하는 방법에 대해 설명합니다. ATTR ( '스타일', ...)하지만, 그것을 사용하는 스타일 속성에 이전에 설정된 스타일을 삭제된다는 경고합니다. 여기에 그 문제없이 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 빈 데모입니다.


  6. 6.다른 답변을 읽고 실험 후이 나를 위해 작동하는 것입니다 :

    다른 답변을 읽고 실험 후이 나를 위해 작동하는 것입니다 :

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

    이것은하지만, IE 8과에서 작동하지 않습니다.


  7. 7.이 작업을 수행 할 수 있습니다 :

    이 작업을 수행 할 수 있습니다 :

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

    속성 이름과 당신이 무엇을 그 값으로 CSS에 추가 원하는대로 "CSSText의"를 사용.


  8. 8.다음과 같은 두 가지 방법을 얻을 수 있습니다 :

    다음과 같은 두 가지 방법을 얻을 수 있습니다 :

    $("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
    $("#elem").attr("style", "width: 100px !important");
    

  9. 9.AramKocharyan의 대답 @의 복잡성,도 동적으로 어떤 스타일 태그를 삽입 할 필요에 갈 필요가 없습니다.

    AramKocharyan의 대답 @의 복잡성,도 동적으로 어떤 스타일 태그를 삽입 할 필요에 갈 필요가 없습니다.

    그냥 덮어 쓰기 스타일,하지만 당신은 왜 것, 아무것도 구문 분석 할 필요는 없습니다?

    // 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' : '') + ';');
    }
    

    그것을 제거하지 않기 때문에, removeProperty ()를 사용할 수 없습니다! 중요한 규칙을 크롬에. 그것은 단지 파이어 폭스에서 낙타 표기법을 허용하기 때문에, = ''element.style [부동산]를 사용할 수 없습니다.

    당신은 아마 jQuery를이 짧은 만들 수 있지만, 바닐라 기능은 최신 브라우저에서 Internet Explorer 8 등을 실행


  10. 10.여기에이 문제가 발생한 이후에 무슨 짓을 ...

    여기에이 문제가 발생한 이후에 무슨 짓을 ...

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

  11. 11.이러한 답변의 대부분은 지금 IE7 지원은 문제가되지 않습니다, 구식이된다.

    이러한 답변의 대부분은 지금 IE7 지원은 문제가되지 않습니다, 구식이된다.

    IE11 + 모든 최신 브라우저를 지원하는이 작업을 수행하는 가장 좋은 방법은 다음과 같습니다

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

    당신이 원하는 경우 또는, 당신은이 작업을 수행 작은 jQuery 플러그인을 만들 수 있습니다. 이 플러그인은 밀접가 지원하는 매개 변수에 jQuery의 자신의 CSS () 메소드를 일치 :

    /**
     * Sets a CSS style on the selected element(s) with !important priority.
     * This supports camelCased CSS style property names and calling with an object 
     * like the jQuery `css()` method. 
     * Unlike jQuery's css() this does NOT work as a getter.
     * 
     * @param {string|Object<string, string>} name
     * @param {string|undefined} value
     */   
    jQuery.fn.cssImportant = function(name, value) {
      const $this = this;
      const applyStyles = (n, v) => {
        // Convert style name from camelCase to dashed-case.
        const dashedName = n.replace(/(.)([A-Z])(.)/g, (str, m1, upper, m2) => {
          return m1 + "-" + upper.toLowerCase() + m2;
        }); 
        // Loop over each element in the selector and set the styles.
        $this.each(function(){
          this.style.setProperty(dashedName, v, 'important');
        });
      };
      // If called with the first parameter that is an object,
      // Loop over the entries in the object and apply those styles. 
      if(jQuery.isPlainObject(name)){
        for(const [n, v] of Object.entries(name)){
           applyStyles(n, v);
        }
      } else {
        // Otherwise called with style name and value.
        applyStyles(name, value);
      }
      // This is required for making jQuery plugin calls chainable.
      return $this;
    };
    
    // Call the new plugin:
    $('#elem').cssImportant('height', '100px');
    
    // Call with an object and camelCased style names:
    $('#another').cssImportant({backgroundColor: 'salmon', display: 'block'});
    
    // Call on multiple items:
    $('.item, #foo, #bar').cssImportant('color', 'red');
    
    

    예 여기 jsfiddle.


  12. 12.이 솔루션은 이전 스타일 중 하나를 오버라이드 (override)하지 않는, 그냥 당신이 필요로하는 하나를 적용 :

    이 솔루션은 이전 스타일 중 하나를 오버라이드 (override)하지 않는, 그냥 당신이 필요로하는 하나를 적용 :

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

  13. 13.당신이 #elem 인 하나 개의 요소로 다루고 있기 때문에 그렇게 관련이없는 그리고 만약 당신이 원하는대로, 당신은 뭔가 다른 스타일을 자사의 ID를 변경할 수 있습니다 ...

    당신이 #elem 인 하나 개의 요소로 다루고 있기 때문에 그렇게 관련이없는 그리고 만약 당신이 원하는대로, 당신은 뭔가 다른 스타일을 자사의 ID를 변경할 수 있습니다 ...

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

    그리고 당신의 CSS에서 :

    #cheaterId { width: 100px;}
    

  14. 14.나에서이 문제에 대한 가장 쉽고 가장 좋은 방법은 단순히 대신에 .css () 또는 .attr ()의) addClass를 (사용하는 것이 었습니다.

    나에서이 문제에 대한 가장 쉽고 가장 좋은 방법은 단순히 대신에 .css () 또는 .attr ()의) addClass를 (사용하는 것이 었습니다.

    예를 들면 :

    $ ( '# 요소') addClass ( 'importantClass.');

    그리고 당신의 CSS 파일 :

    .importantClass {
        width: 100px !important;
    }
    

  15. 15.대신 CSS () 함수는 addClass () 함수를하려고 사용 :

    대신 CSS () 함수는 addClass () 함수를하려고 사용 :

      <script>
      $(document).ready(function() {
        $("#example").addClass("exampleClass");
      });
      </script>
    
      <style>
      .exampleClass{
        width:100% !important;
        height:100% !important;
      }
      </style>
    

  16. 16.jQuery를 지원하지 않기 때문에 참고로, 작동하지 않습니다. 2012 년에 제기 티켓 결국 고치지 않을 것 (wontfix)로 폐쇄되었다 ((ELEM) .CSS ( "속성", "가치! 중요한") 실패 # 11173 $)가 있었다.

    jQuery를 지원하지 않기 때문에 참고로, 작동하지 않습니다. 2012 년에 제기 티켓 결국 고치지 않을 것 (wontfix)로 폐쇄되었다 ((ELEM) .CSS ( "속성", "가치! 중요한") 실패 # 11173 $)가 있었다.


  17. 17.우리는 이전 스타일을 제거하기 위해 먼저해야합니다. 나는 정규 표현식을 사용하여 제거합니다. 여기서 색상을 변경하는 예이다 :

    우리는 이전 스타일을 제거하기 위해 먼저해야합니다. 나는 정규 표현식을 사용하여 제거합니다. 여기서 색상을 변경하는 예이다 :

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

  18. 18.머리에 APPEND 스타일에 다른 방법 :

    머리에 APPEND 스타일에 다른 방법 :

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

    그것은 다른 CSS 파일보다 더 높은 우선 순위를 가지고하고 적용 할 수 있도록이 모든 CSS 파일 이후에 스타일을 추가합니다.


  19. 19.이 같은의를 볼 수있다 :

    이 같은의를 볼 수있다 :

    var node = $('.selector')[0];
    OR
    var node = document.querySelector('.selector');
    
    node.style.setProperty('width', '100px', 'important');
    node.style.removeProperty('width');
    OR
    node.style.width = '';

  20. 20.(: DOM 요소이) 나는 그것이 OK를 작동하기 전에 다른 CSS를 덮어 쓸 수 있다고 생각합니다 :

    (: DOM 요소이) 나는 그것이 OK를 작동하기 전에 다른 CSS를 덮어 쓸 수 있다고 생각합니다 :

    this.setAttribute('style', 'padding:2px !important');
    

  21. 21.이 솔루션은 모든 계산 자바 스크립트를 떠나 요소에 중요한 태그를 추가합니다 : (당신이 중요한 태그로 폭을 설정해야하는 경우 예)를 당신은 할 수있다

    이 솔루션은 모든 계산 자바 스크립트를 떠나 요소에 중요한 태그를 추가합니다 : (당신이 중요한 태그로 폭을 설정해야하는 경우 예)를 당신은 할 수있다

    $('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
    

  22. 22.이런 식으로 작업을 수행 :

    이런 식으로 작업을 수행 :

    $("#elem").get(0).style.width= "100px!important";
    

  23. 23.나는 비슷한 상황이 있었다, 그러나 나는 많은 변화와 장시간 () .closest과 사투를 벌인 후 () .find 사용.

    나는 비슷한 상황이 있었다, 그러나 나는 많은 변화와 장시간 () .closest과 사투를 벌인 후 () .find 사용.

    // 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
    });
    
    $('.inner').each(function () {
        this.style.setProperty('height', '50px', 'important');
    });
    
    $('#out').find('.inner').css({ 'height': '50px'});
    

    작업 : http://jsfiddle.net/fx4mbp6c/


  24. 24.그것은 또는 상황에 적절하지 않을 수 있습니다하지만 당신은 상황이 유형의 많은에 대한 CSS 선택기를 사용할 수 있습니다.

    그것은 또는 상황에 적절하지 않을 수 있습니다하지만 당신은 상황이 유형의 많은에 대한 CSS 선택기를 사용할 수 있습니다.

    당신이 3, .cssText의 6 번째 인스턴스의 원 예를 들어, 당신이 쓸 수있는 폭이 다른을 가지고 :

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

    또는:

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

  25. 25.난 당신이 추가! 중요하지 않고 그것을 시도 가정 것인가?

    난 당신이 추가! 중요하지 않고 그것을 시도 가정 것인가?

    (자바 스크립트 스타일을 추가하는 방법입니다) 인라인 CSS 스타일 시트의 CSS를 무시합니다. 나는 확신 중요한 스타일 시트 CSS 규칙에도 케이스! 있다고 해요.

    (. 어쩌면 바보 같은 질문이지만 질문해야합니다) 또 다른 질문 : 당신은 디스플레이에 작업하려고하는 요소입니다 : 블록; 또는 디스플레이 인라인 블록;?

    사용자가 예상하는대로 CSS에서 전문 지식을 알면서 ... 인라인 요소는 항상 작동하지 않습니다.


  26. 26.우리는 추가 setProperty는 또는 CSSText의를 사용할 수 있습니다! 중요한 자바 스크립트를 사용하여 DOM 요소에.

    우리는 추가 setProperty는 또는 CSSText의를 사용할 수 있습니다! 중요한 자바 스크립트를 사용하여 DOM 요소에.

    예 1 :

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

    예 2 :

    elem.style.cssText='color: red !important;'
    

  27. 27.또한 발견 된 그 어떤 요소 나 추가 기능 (부트 스트랩 등)의 그들과 함께! .addClass / .removeClass 같은 중요하거나 다른 작업 어라운드 잘 작동하지 않는 일부 특수 학급의 경우가 있고, 따라서 당신은 / 그들을 전환해야 떨어져서.

    또한 발견 된 그 어떤 요소 나 추가 기능 (부트 스트랩 등)의 그들과 함께! .addClass / .removeClass 같은 중요하거나 다른 작업 어라운드 잘 작동하지 않는 일부 특수 학급의 경우가 있고, 따라서 당신은 / 그들을 전환해야 떨어져서.

    당신이 <표 클래스 = "테이블 호버"> 유일한 방법 같은 것을 사용하는 경우 행의 색상에 / 테이블 - 호버 클래스를 전환 할 수있는 것처럼 예를 들어, 성공적으로이 같은 요소를 수정할

    $ (your_element) .closest ( "테이블") toggleClass ( "테이블 가져가.");

    희망이 해결 방법은 사람에게 도움이 될 것입니다! :)


  28. 28.나는 메뉴 항목 "이벤트"의 텍스트 색상을 변경하려고 같은 문제가 있었다. 나는이 같은 문제가 있었다했을 때 가장 좋은 방법은 내가 발견

    나는 메뉴 항목 "이벤트"의 텍스트 색상을 변경하려고 같은 문제가 있었다. 나는이 같은 문제가 있었다했을 때 가장 좋은 방법은 내가 발견

    첫 번째 단계는 예를 들어,이 목적으로, 당신의 CSS에서, 새로운 클래스를 생성합니다 :

    .colorw{ color: white !important;}
    

    마지막 단계는 다음과 같이 addClass 방법을 사용하여이 클래스를 적용 :

    $('.menu-item>a').addClass('colorw');
    

    문제 해결됨.


  29. 29.이에 대한 가장 안전한 해결 방법은 :-) 작업을 수행해야합니다 addClass ()와 removeClass () 클래스를 추가하는 것입니다 다음 CSS에 마법을한다.

    이에 대한 가장 안전한 해결 방법은 :-) 작업을 수행해야합니다 addClass ()와 removeClass () 클래스를 추가하는 것입니다 다음 CSS에 마법을한다.


  30. 30.https://jsfiddle.net/xk6Ut/256/

    https://jsfiddle.net/xk6Ut/256/

    다른 방법은 동적으로 생성하고 자바 스크립트로 CSS 클래스를 업데이트하고 있습니다. 우리는 CSS 클래스를 업데이트 할 수 있도록이를 위해, 우리는 스타일 요소에 대한 ID를 사용하는 스타일 요소와 필요를 사용할 수 있습니다

    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)
    
  31. from https://stackoverflow.com/questions/2655925/how-to-apply-important-using-css by cc-by-sa and MIT license