mko*_*yak 700 html javascript css jquery
我在应用一种风格时遇到了麻烦!important
.我试过了:
$("#elem").css("width", "100px !important");
Run Code Online (Sandbox Code Playgroud)
这什么都不做 ; 没有任何宽度样式应用.是否有jQuery-ish方式应用这样的样式而不必覆盖cssText
(这意味着我需要先解析它等等)?
编辑:我应该补充一点,我有一个样式表!important
,我试图用!important
样式内联覆盖一个样式,所以使用等等.width()
不起作用,因为它被我的外部!important
样式覆盖.
此外,将覆盖以前的值的值进行计算,所以我不能简单地创建另一个外部风格.
Dav*_*mas 577
问题是由jQuery不理解该!important
属性引起的,因此无法应用该规则.
您可以解决该问题,并通过引用来应用规则,方法是addClass()
:
.importantRule { width: 100px !important; }
$('#elem').addClass('importantRule');
Run Code Online (Sandbox Code Playgroud)
或者使用attr()
:
$('#elem').attr('style', 'width: 100px !important');
Run Code Online (Sandbox Code Playgroud)
然而,后一种方法将取消任何先前设置的内联样式规则.所以要小心使用.
当然,有一个很好的论据,@ Nick Craver的方法更容易/更明智.
上面的attr()
方法略有修改,以保留原始style
字符串/属性:
$('#elem').attr('style', function(i,s) { return (s || '') + 'width: 100px !important;' });
Run Code Online (Sandbox Code Playgroud)
Ara*_*yan 329
我想我找到了一个真正的解决方案.我把它变成了一个新功能:
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'));
Run Code Online (Sandbox Code Playgroud)
这是输出:
null
red
blue
important
Run Code Online (Sandbox Code Playgroud)
(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);
Run Code Online (Sandbox Code Playgroud)
请参见本有关如何读取和设置CSS值的例子.我的问题是我已经!important
在我的CSS中设置宽度以避免与其他主题CSS发生冲突,但是我在jQuery中对宽度所做的任何更改都不会受到影响,因为它们会被添加到style属性中.
为了使用该setProperty
功能进行优先级设置,本文称支持IE 9+和所有其他浏览器.我已经尝试使用IE 8并且它已经失败了,这就是为什么我在我的函数中构建了对它的支持(参见上文).它将适用于使用setProperty的所有其他浏览器,但它需要我的自定义代码才能在<IE 9中工作.
Nic*_*ver 143
您可以直接使用.width()
如下设置宽度:
$("#elem").width(100);
Run Code Online (Sandbox Code Playgroud)
更新评论: 你也有这个选项,但它会替换元素上的所有css,所以不确定它是否更可行:
$('#elem').css('cssText', 'width: 100px !important');
Run Code Online (Sandbox Code Playgroud)
小智 76
var elem = $("#elem");
elem[0].style.removeAttribute('width');
elem[0].style.setProperty('width', '100px', 'important');
Run Code Online (Sandbox Code Playgroud)
Ror*_*ane 54
David Thomas的回答描述了一种使用方法$('#elem').attr('style', …)
,但警告说使用它将删除style
属性中先前设置的样式.这是一种attr()
没有这个问题的使用方法:
var $elem = $('#elem');
$elem.attr('style', $elem.attr('style') + '; ' + 'width: 100px !important');
Run Code Online (Sandbox Code Playgroud)
作为一个功能:
function addStyleAttribute($element, styleAttribute) {
$element.attr('style', $element.attr('style') + '; ' + styleAttribute);
}
Run Code Online (Sandbox Code Playgroud)
addStyleAttribute($('#elem'), 'width: 100px !important');
Run Code Online (Sandbox Code Playgroud)
这是一个JS Bin演示.
Nat*_*ate 29
在阅读其他答案并进行实验后,这对我有用:
$(".selector")[0].style.setProperty( 'style', 'value', 'important' );
Run Code Online (Sandbox Code Playgroud)
但是,这在IE 8及以下版本中不起作用.
haw*_*126 26
你可以这样做:
$("#elem").css("cssText", "width: 100px !important;");
Run Code Online (Sandbox Code Playgroud)
使用"cssText"作为属性名称以及您想要添加到CSS的任何值作为其值.
mko*_*yak 20
大多数这些答案现在已经过时,IE7 支持不是问题。
支持 IE11+ 和所有现代浏览器的最佳方法是:
const $elem = $("#elem");
$elem[0].style.setProperty('width', '100px', 'important');
Run Code Online (Sandbox Code Playgroud)
或者,如果您愿意,您可以创建一个小型 jQuery 插件来执行此操作。这个插件css()
在它支持的参数上与 jQuery 自己的方法非常匹配:
/**
* 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;
};
Run Code Online (Sandbox Code Playgroud)
// 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');
Run Code Online (Sandbox Code Playgroud)
kva*_*kva 18
您可以通过两种方式实现此目的:
$("#elem").prop("style", "width: 100px !important"); // this is not supported in chrome
$("#elem").attr("style", "width: 100px !important");
Run Code Online (Sandbox Code Playgroud)
Has*_*own 14
没有必要考虑@ 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' : '') + ';');
}
Run Code Online (Sandbox Code Playgroud)
无法使用removeProperty()
,因为它不会删除!important
Chrome 中的规则.
无法使用element.style[property] = ''
,因为它只接受Firefox中的camelCase.
你可以用jQuery缩短它,但这个vanilla函数可以在现代浏览器,Internet Explorer 8等上运行.
keb*_*ang 12
这是我在遇到这个问题后所做的......
var origStyleContent = jQuery('#logo-example').attr('style');
jQuery('#logo-example').attr('style', origStyleContent + ';width:150px !important');
Run Code Online (Sandbox Code Playgroud)
如果它不是那么相关,并且因为你正在处理一个元素#elem
,你可以将它的id更改为其他东西并根据你的意愿设置它...
$('#elem').attr('id', 'cheaterId');
Run Code Online (Sandbox Code Playgroud)
在你的CSS中:
#cheaterId { width: 100px;}
Run Code Online (Sandbox Code Playgroud)
此解决方案不会覆盖任何以前的样式,它只应用您需要的样式:
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);
}
Run Code Online (Sandbox Code Playgroud)
小智 8
而不是使用该css()
函数尝试该addClass()
函数:
<script>
$(document).ready(function() {
$("#example").addClass("exampleClass");
});
</script>
<style>
.exampleClass{
width:100% !important;
height:100% !important;
}
</style>
Run Code Online (Sandbox Code Playgroud)
对我来说这个问题的最简单和最好的解决方案是简单地使用addClass()而不是.css()或.attr().
例如:
$('#elem').addClass('importantClass');
在你的CSS文件中:
.importantClass {
width: 100px !important;
}
Run Code Online (Sandbox Code Playgroud)
我们首先需要删除以前的样式.我使用正则表达式删除它.这是一个改变颜色的例子:
var SetCssColorImportant = function (jDom, color) {
var style = jDom.attr('style');
style = style.replace(/color: .* !important;/g, '');
jDom.css('cssText', 'color: ' + color + ' !important;' + style); }
Run Code Online (Sandbox Code Playgroud)
在头部追加样式的另一种方法:
$('head').append('<style> #elm{width:150px !important} </style>');
Run Code Online (Sandbox Code Playgroud)
这会在所有CSS文件之后添加样式,因此它将具有比其他CSS文件更高的优先级并将被应用.
可能看起来像这样:
var node = $('.selector')[0]; OR var node = document.querySelector('.selector');
node.style.setProperty('width', '100px', 'important');
node.style.removeProperty('width'); OR node.style.width = '';
我认为它工作正常,并且可以覆盖之前的任何其他CSS(此:DOM元素):
this.setAttribute('style', 'padding:2px !important');
Run Code Online (Sandbox Code Playgroud)
小智 5
像这样做:
$("#elem").get(0).style.width= "100px!important";
Run Code Online (Sandbox Code Playgroud)
此解决方案将保留所有计算出的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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
529675 次 |
最近记录: |