Program Club

Javascript | jQuery로 특정 인라인 스타일 제거

proclub 2020. 12. 15. 19:32
반응형

Javascript | jQuery로 특정 인라인 스타일 제거


내 HTML에 다음 코드가 있습니다.

<p id='foo' style='text-align:center; font-size:14pt; font-family:verdana; color:red'>hello world</p>

그리고 내 외부 CSS에서 :

#foo{ font-size:11pt; font-family:arial; color:#000; }

"스타일"속성에서 모든 "글꼴 크기"및 "글꼴-패밀리"를 제거하고 싶지만 "색상"및 외부 CSS에 설정된 다른 항목은 제거하지 않습니다.

예상 결과 :

<p id='foo' style='text-align:center; color:red'>hello world</p>

이미 시도 :

$('#foo').removeAttr('style');   // That removes all inline
$('#foo').css('font-family',''); // That remove the css setted too

jQuery를 사용하지 않는 경우 기본 removeProperty 메서드를 사용하여 인라인 스타일에서 특정 스타일을 삭제할 수 있습니다 . 예:

elem.style.removeProperty('font-family');

물론 IE <9는이를 지원하지 않으므로 사용해야합니다.

elem.style.removeAttribute('font-family');

이를 수행하는 크로스 브라우저 방법은 다음과 같습니다.

if (elem.style.removeProperty) {
    elem.style.removeProperty('font-family');
} else {
    elem.style.removeAttribute('font-family');
}

속성을 inherit다음과 같이 설정합니다 .

$('#foo').css('font-family','inherit').css('font-size','inherit');

이 문제에 대한 적절한 해결책이 없다고 생각합니다 (마크 업을 변경하지 않고). 스타일 속성의 값을 검색하고 바꿀 수 있습니다.

var element = $('#foo');
element.attr('style', element.attr('style').replace(/font-size:[^;]+/g, '').replace(/font-family:[^;]+/g, ''))

지금까지 가장 좋은 해결책은 인라인 스타일을 제거하고 클래스를 사용하여 스타일을 관리하는 것입니다.


내 제안은 인라인 스타일을 사용하여이 항목을 설정하지 않는 것입니다. 클래스를 사용한 다음 jQuery를 사용하여 클래스간에 전환하는 것이 좋습니다.

CSS :

#foo{ font-size:11pt; font-family:arial; color:#000; }
#foo.highlight {text-align:center; font-size:14pt; font-family:verdana; color:red}

HTML :

<p id="foo" class="highlight">hello world</p>

자바 스크립트 :

$('#foo').removeClass('highlight');
$('#foo').addClass('highlight');

2019 년에 속성을 제거하는 가장 간단한 방법은 다음과 같습니다.

elem.style.border = "";

마찬가지로 테두리를 설정하려면 :

elem.style.outline = "1px solid blue";

모든 브라우저에서도 작동해야합니다!


내가 볼 수 있듯이 단락에 대해 두 가지 다른 스타일이 필요합니다. CSS에서 설정 한 다음 jQuery를 사용하여 필요에 따라 제거 / 추가하는 것이 더 쉬울 수 있습니다.

#styleOne { color: red; font: normal 14pt Verdana; text-align: center; }

#styleTwo{ color: #000; font: normal 11pt Arial; text-align: center; }

초기 HTML은 다음과 같습니다.

<p id="styleOne">hello world</p>

그런 다음 jQuery에서 styleTwo로 되돌리려면

$('p#styleOne').removeClass('styleOne').addClass('styleTwo');

참조 URL : https://stackoverflow.com/questions/4033004/remove-a-specific-inline-style-with-javascriptjquery

반응형