Nice programing

.css () 함수로 추가 된 스타일을 제거하려면 어떻게해야합니까?

nicepro 2020. 9. 28. 10:05
반응형

.css () 함수로 추가 된 스타일을 제거하려면 어떻게해야합니까?


jQuery로 CSS를 변경하고 있으며 입력 값에 따라 추가하는 스타일을 제거하고 싶습니다.

if(color != '000000') $("body").css("background-color", color); else // remove style ?

어떻게 할 수 있습니까? 위의 선은 색상 선택기를 사용하여 색상을 선택할 때마다 실행됩니다 (예 : 마우스가 색상환 위로 이동할 때).

두 번째 참고 : css("background-color", "none")CSS 파일에서 기본 스타일링을 제거하기 때문에이 작업을 수행 할 수 없습니다 . background-colorjQuery에서 추가 한 인라인 스타일 을 제거하고 싶습니다 .


속성을 빈 문자열로 변경하면 작업을 수행하는 것처럼 보입니다.

$.css("background-color", "");

허용되는 답변 은 작동하지만 style테스트에서 DOM에 속성을 남깁니다 . 큰 문제는 아니지만 이것은 모든 것을 제거합니다.

removeAttr( 'style' );

이것은 모든 동적 스타일을 제거하고 스타일 시트 스타일로 돌아 가기를 원한다고 가정합니다.


jQuery를 사용하여 CSS 속성을 제거하는 방법에는 여러 가지가 있습니다.

1. CSS 속성을 기본 (초기) 값으로 설정

.css("background-color", "transparent")

MDN에서 CSS 속성초기 값을 참조하십시오 . 여기서 기본값은 transparent입니다. inherit여러 CSS 속성을 사용 하여 부모로부터 속성을 상속 할 수도 있습니다 . CSS3 / CSS4, 당신은 또한 사용할 수 있습니다 initial, revert또는 unset그러나이 키워드는 제한된 브라우저 지원이있을 수 있습니다.

2. CSS 속성 제거

빈 문자열은 CSS 속성을 제거합니다.

.css("background-color","")

그러나 jQuery .css () 문서에 지정된 대로이 속성은 제거되지만 background를 포함한 특정 CSS 속기 속성에 대해 IE8과의 호환성 문제가 있습니다.

스타일 속성의 값을 빈 문자열 (예 : $ ( '# mydiv'). css ( 'color', ''))로 설정하면 HTML 스타일에 관계없이 이미 직접 적용된 경우 요소에서 해당 속성이 제거됩니다. 속성, jQuery의 .css () 메서드를 통해 또는 스타일 속성의 직접 DOM 조작을 통해. 그러나 스타일 시트 또는 요소에서 CSS 규칙으로 적용된 스타일을 제거하지는 않습니다. 경고 : 한 가지 주목할만한 예외는 IE 8 이하의 경우 테두리 또는 배경과 같은 속기 속성을 제거하면 스타일 시트 또는 요소에 설정된 항목에 관계없이 요소에서 해당 스타일이 완전히 제거된다는 것입니다 .

3. 요소의 전체 스타일 제거

.removeAttr("style")

순수한 JavaScript의 방법을 알려주기 위해 순수한 JavaScript로 스타일 속성을 제거하는 방법이 있습니다.

var bodyStyle = document.body.style;
if (bodyStyle.removeAttribute)
    bodyStyle.removeAttribute('background-color');
else        
    bodyStyle.removeProperty('background-color');

완전한 태그가 제거됩니다.

  $("body").removeAttr("style");

다음 jQuery 함수 중 하나가 작동해야합니다.

$("#element").removeAttr("style");
$("#element").removeAttr("background-color") 

다음과 같은 것은 어떻습니까?

var myCss = $(element).attr('css');
myCss = myCss.replace('background-color: '+$(element).css('background-color')+';', '');
if(myCss == '') {
  $(element).removeAttr('css');
} else {
  $(element).attr('css', myCss);
}

이 시도:

$('#divID').css({"background":"none"});// remove existing

$('#divID').css({"background":"#bada55"});// add new color here.

감사


그냥 사용 :

$('.tag-class').removeAttr('style');

또는

$('#tag-id').removeAttr('style');

CSS 스타일을 사용하는 경우 다음을 사용할 수 있습니다.

$("#element").css("background-color","none"); 

다음으로 대체하십시오.

$("#element").css("background-color", color);

CSS 스타일을 사용하지 않고 HTML 요소에 속성이있는 경우 다음을 사용할 수 있습니다.

$("#element").attr("style.background-color",color);

내 플러그인 사용 :

$.fn.removeCss=function(all){
        if(all===true){
            $(this).removeAttr('class');
        }
        return $(this).removeAttr('style')
    }

귀하의 경우 다음과 같이 사용하십시오.

$(<mySelector>).removeCss();

또는

$(<mySelector>).removeCss(false);

클래스에 정의 된 CSS도 제거하려면 다음을 수행하십시오.

$(<mySelector>).removeCss(true);

2018 년

이를위한 네이티브 API가 있습니다.

element.style.removeProperty(propery)

이것도 작동합니다 !!

$elem.attr('style','');

CSS 클래스를 제거하고 싶은 스타일을 만들어 보지 않겠습니까? 이제 다음을 사용할 수 있습니다 .removeClass().. 이것은 또한 다음을 사용할 가능성을 열어줍니다..toggleClass()

(있는 경우 클래스를 제거하고 없으면 추가하십시오.)

클래스 추가 / 제거는 레이아웃 문제를 처리 할 때 변경 / 문제 해결에 덜 혼란 스럽습니다 (특정 스타일이 사라진 이유를 알아 내려는 것과 반대).


let el = document.querySelector(element)
let styles = el.getAttribute('style')

el.setAttribute('style', styles.replace('width: 100%', ''))

This is more complex than some other solutions, but may offer more flexibility in scenarios:

1) Make a class definition to isolate (encapsulate) the styling you want to apply/remove selectively. It can be empty (and for this case, probably should be):

.myColor {}

2) use this code, based on http://jsfiddle.net/kdp5V/167/ from this answer by gilly3:

function changeCSSRule(styleSelector,property,value) {
    for (var ssIdx = 0; ssIdx < document.styleSheets.length; ssIdx++) {
        var ss = document.styleSheets[ssIdx];
        var rules = ss.cssRules || ss.rules;
        if(rules){
            for (var ruleIdx = 0; ruleIdx < rules.length; ruleIdx++) {
                var rule = rules[ruleIdx];
                if (rule.selectorText == styleSelector) {
                    if(typeof value == 'undefined' || !value){
                        rule.style.removeProperty(property);
                    } else {
                        rule.style.setProperty(property,value);
                    }
                    return; // stops at FIRST occurrence of this styleSelector
                }
            }
        }
    }
}

Usage example: http://jsfiddle.net/qvkwhtow/

Caveats:

  • Not extensively tested.
  • Can't include !important or other directives in the new value. Any such existing directives will be lost through this manipulation.
  • Only changes first found occurrence of a styleSelector. Doesn't add or remove entire styles, but this could be done with something more elaborate.
  • Any invalid/unusable values will be ignored or throw error.
  • In Chrome (at least), non-local (as in cross-site) CSS rules are not exposed through document.styleSheets object, so this won't work on them. One would have to add a local overrides and manipulate that, keeping in mind the "first found" behavior of this code.
  • document.styleSheets is not particularly friendly to manipulation in general, don't expect this to work for aggressive use.

Isolating the styling this way is what CSS is all about, even if manipulating it isn't. Manipulating CSS rules is NOT what jQuery is all about, jQuery manipulates DOM elements, and uses CSS selectors to do it.


Simple is cheap in web development. I recommend using empty string when removing a particular style

$(element).style.attr = '  ';

Try This

$(".ClassName").css('color','');
Or 
$("#Idname").css('color','');

참고URL : https://stackoverflow.com/questions/4036857/how-can-i-remove-a-style-added-with-css-function

반응형