.css()를 사용하여 !important를 적용하는 방법
이런 스타일을 적용하는 데 어려움을 겪고 있습니다.!important력했습습니니다
$("#elem").css("width", "100px !important");
이것은 아무것도 하지 않습니다.폭 스타일은 전혀 적용되지 않습니다.이러한 스타일을 덮어쓰지 않고 적용할 수 있는 jQuery 같은 방법이 있습니까?cssText(비밀번호)
Edit: 스타일시트가 있다는 것을 추가해야 합니다.!important style with with that that 하는 스타일!important inline이므로, 「」를 사용합니다..width(), 되어 버리기 에, 같은 하지 않습니다.!importantstylecontraction을 합니다.
또한 이전 값을 덮어쓰는 값이 계산되므로 다른 외부 스타일을 쉽게 만들 수 없습니다.
가 jQuery를 하지 못하기 때문에 합니다.!importantAttribute ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★」
할 수 .addClass():
.importantRule { width: 100px !important; }
$('#elem').addClass('importantRule');
'어느 정도'를 attr():
$('#elem').attr('style', 'width: 100px !important');
그러나 후자의 접근방식은 이전에 설정된 인라인 스타일 규칙을 설정하지 않습니다.그러니 조심해서 사용하세요.
물론 @Nick Craver의 방법이 더 쉽거나 더 쉽다는 좋은 주장도 있다.
'아예'는,attr()됩니다.stylestring/properties 및 falko가 코멘트에서 제안한 대로 수정합니다.
$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });
해결책을 찾은 것 같아새로운 기능으로 만들었습니다.
jQuery.style(name, value, priority);
해서 이 수 ..style('name').css('name'), 를 입수하다.style()priority를 '중요'로 지정하는 기능을 사용하여 값을 설정합니다.이것 좀 봐.
예
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의 폭에 대한 변경은 스타일 속성에 추가되기 때문에 영향을 받지 않습니다.
호환성.
이 문서에서는 이 기능을 사용하여 우선순위를 설정하는 경우 IE 9+ 및 기타 모든 브라우저가 지원된다고 합니다.IE 8을 사용해 보았지만 실패했기 때문에 기능적으로 지원을 구축했습니다(위 참조).다른 모든 브라우저에서도 동작합니다.setProperty, < 9> < IE 9 > < IE 9 > 에서는 커스텀 코드가
다음과 같이 직접 폭을 설정할 수 있습니다.
$("#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');
다른 답을 읽고 실험해 본 결과, 다음과 같이 할 수 있습니다.
$(".selector")[0].style.setProperty( 'style', 'value', 'important' );
IE 8 이하에서는 동작하지 않습니다.
다음과 같이 할 수 있습니다.
$("#elem").css("cssText", "width: 100px !important;");
속성명으로서 「cssText」를 사용하고, 그 값으로서 CSS에 추가하는 것을 사용합니다.
이러한 답변의 대부분은 구식이므로 IE7 지원은 문제가 되지 않습니다.
IE11+ 및 모든 최신 브라우저를 지원하는 가장 좋은 방법은 다음과 같습니다.
const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');
또는 필요에 따라 이를 수행하는 작은 jQuery 플러그인을 만들 수 있습니다.의 jQuery와 일치합니다.css()in in in지지 method method method 。
/**
* 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');
이것은, 다음의 2개의 방법으로 실행할 수 있습니다.
$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
@Aram Kocharyan의 답변의 복잡함이나 스타일 태그를 동적으로 삽입할 필요가 없습니다.
스타일을 덮어쓸 뿐이지 구문 분석할 필요는 없어, 왜?
// 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()되지 않기!important규칙을 지정합니다.
할 수 element.style[property] = ''낙타 사건
jQuery를 사용하면 단축할 수 있지만 이 바닐라 기능은 최신 브라우저, Internet Explorer 8 등에서 실행됩니다.
이 문제에 부딪힌 후 제가 한 일은 다음과 같습니다.
var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
이 솔루션은 이전 스타일을 재정의하지 않고 필요한 스타일만 적용합니다.
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);
}
만약 그게 그렇게 적절하지 않다면 그리고 당신이 한 가지 요소를 다루고 있기 때문에#elem를 다른
$('#elem').attr('id', 'cheaterId');
그리고 CSS에서는:
#cheaterId { width: 100px;}
이 문제에 대한 가장 쉽고 최선의 해결책은 단순히 .css() 또는 .attr() 대신 addClass()를 사용하는 것이었습니다.
예를 들어 다음과 같습니다.
$('#elem').addClass('importantClass');
CSS 파일에는 다음과 같은 것이 있습니다.
.importantClass {
width: 100px !important;
}
「 」를하는 대신에, 「 」를 사용합니다.css()합니다.addClass()★★★★
<script>
$(document).ready(function() {
$("#example").addClass("exampleClass");
});
</script>
<style>
.exampleClass{
width:100% !important;
height:100% !important;
}
</style>
참고로, jQuery가 지원하지 않기 때문에 작동하지 않습니다.2012년에 제출된 티켓(#11173 $(elem.css("property", "value!important") fails)가 최종적으로 UNTFIX로 마감되었습니다.
먼저 이전 스타일을 삭제해야 합니다.정규 표현으로 지웁니다.다음은 색상의 변경 예를 제시하겠습니다.
var SetCssColorImportant = function (jDom, color) {
var style = jDom.attr('style');
style = style.replace(/color: .* !important;/g, '');
jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
머리에 스타일을 추가하는 다른 방법:
$('head').append('<style> #elm{width:150px !important} </style>');
이것은 모든 CSS 파일 뒤에 스타일을 추가하기 때문에 다른 CSS 파일보다 높은 우선순위를 가지며 적용됩니다.
이렇게 생겼을 수도 있습니다.
캐시
var 노드 = $(.syslog')[0];
또는var node = 문서.query Selector(''선택자');
CSS 설정
node.style.setProperty("width", "100px", "important");
CSS 삭제
node.style.removeProperty('width');
또는node.style.폭 = ';정상적으로 동작하며 이전에 다른 CSS를 덮어쓸 수 있다고 생각합니다(DOM 요소).
this.setAttribute('style', 'padding:2px !important');
다음과 같이 합니다.
$("#elem").get(0).style.width= "100px!important";
이 솔루션은 계산된 javascript를 모두 남겨두고 중요한 태그를 요소에 추가합니다.할 수 있다(중요한 태그로 폭을 설정할 필요가 있는 경우)
$('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
3가지 작업 예
저도 비슷한 상황이었지만 .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/
상황에 따라서는 적절할 수도 있고 적합하지 않을 수도 있지만 이러한 유형의 많은 경우 CSS 셀렉터를 사용할 수도 있습니다.
예를 들어 .cssText의 세 번째 및 여섯 번째 인스턴스에서 다른 너비를 원하는 경우 다음과 같이 쓸 수 있습니다.
.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;}
안 넣었을 거예요.!important
CSS (JavaScript) : CSS (JavaScript ) 。에 「CSS」라고 하는 것이 합니다.!important.
하나의 질문 바보 질문해야 는 '어느 요소'입니까?display:block; ★★★★★★★★★★★★★★★★★」display:inline-block;
CSS에 대한 전문지식을 모르기 때문에 인라인 요소가 항상 예상대로 동작하지는 않습니다.
setProperty 하여 setProperty의 cssText를 할 수 .!importantJavaScript java java java DOM java java java java java java 。
예 1:
elem.style.setProperty ("color", "green", "important");
예 2:
elem.style.cssText='color: red !important;'
, 은, 「」, 「」, 「부트스트랩」등의 특수한 되었습니다.!important 외의 도 있습니다..addClass/.removeClass라오오/오오를를를를를오오 오오오오오오
를 들어, 예를 들어 '아까보다'와 같은 요.<table class="table-hover">은 색상/색상/색상/색상/색상/Color/입니다.table-hover 온)
$(your_element).closest("table").toggleClass("table-hover");
이 회피책이 누군가에게 도움이 되었으면 합니다. :)
이벤트 시 메뉴 항목의 텍스트 색상을 변경하려고 해도 같은 문제가 있었습니다.같은 문제가 생겼을 때 가장 좋은 방법은 다음과 같습니다.
첫 번째 순서: CSS에서 이 목적을 가진 새 클래스를 만듭니다.다음은 다음과 같습니다.
.colorw{ color: white !important;}
마지막 단계: 다음과 같이 addClass 메서드를 사용하여 이 클래스를 적용합니다.
$('.menu-item>a').addClass('colorw');
문제는 해결됐습니다.
를 위한 안전한 한 후 CSS CSS :-), CSS :-)에서입니다.addClass() ★★★★★★★★★★★★★★★★★」removeClass()할 수 있을 거야
https://jsfiddle.net/xk6Ut/256/
대체 접근법은 JavaScript에서 동적으로 CSS 클래스를 만들고 업데이트하는 것입니다.이를 위해 스타일 요소를 사용할 수 있으며 스타일 요소의 ID를 사용하여 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)
언급URL : https://stackoverflow.com/questions/2655925/how-to-apply-important-using-css
'programing' 카테고리의 다른 글
| JavaScript에서 번호가 NaN인지 확인하려면 어떻게 해야 합니까? (0) | 2022.10.06 |
|---|---|
| mysqli가 영속적인 접속을 재접속할 때 "서버가 사라졌습니다"라는 경고를 수정하려면 어떻게 해야 합니까? (0) | 2022.10.06 |
| bootstrap-vue 선택 옵션 내부에 이미지 삽입 (0) | 2022.10.06 |
| argparse를 사용하여 목록을 명령줄 인수로 전달하려면 어떻게 해야 합니까? (0) | 2022.09.30 |
| javax.persistence를 사용할 수 있습니다.Query.getResultList()가 null을 반환하시겠습니까? (0) | 2022.09.30 |