如何使用jquery覆盖包含’!important’的css?

我想使用jquery为特定div应用height ,但不能使用jquery覆盖'!important'关键字。

这是标记:

 
sometext here
sometext here
sometext here
sometext here

CSS:

 .myclass{ height:50px !important; } 

在这里,我想找到class “myclass”,其中divid等于“divL3”

我试过:

 $('#divL3.myclass').css('height', '0px'); 

但不会工作! 那么,如何'!important' css using jquery覆盖'!important' css using jquery

帮助赞赏!

试试这个 :

 $( '.myclass' ).each(function () { this.style.setProperty( 'height', '0px', 'important' ); }); 

.setProperty()使您可以传递表示优先级的第三个参数。

另一个简单的方法来解决这个问题添加样式属性。

 $('.selector').attr('style','width:500px !important'); 

这将很容易解决你的问题… 🙂

你可以这样做:

 $(".myclass").css("cssText", "height: 0 !important;"); 

使用“cssText”作为属性名称以及您想要添加到css的任何值作为它的值。

内联样式无法覆盖样式表中给出的!important。

因此!important只能通过使用!important沿jQuery重写

试试吧

 $('#divL3.myclass').attr('style', 'height: 0px !important'); 

这将像一个魅力

  $( '#divL3' ).css("cssText", "height: 0px !important;") 

这里是小提琴http://jsfiddle.net/abhiklpm/Z3WHM/2/

完成它还有另外一个技巧! 你可以从元素中删除myclass并应用高度。 喜欢

 $('#divL3.myclass').removeClass('myclass').css('height', '0px'); 

First Id是唯一标识符,因此您不需要通过它的类名搜索div。 因此你可以通过它的id过滤div。

请尝试以下代码

首先在myClass下添加新的Class属性,如下所示

  

它将覆盖myClass的height属性

现在只需将此类添加到div

 $('#divL3').addClass('testClass'); 

但制作高度“0”不会隐藏“divL3”的内容。 您宁愿尝试隐藏溢出内容或通过添加css属性display:none来隐藏整个div

希望它能为你效劳。

没有use.suppose如果我在风格attribure.it中有一些css属性将无法正常工作。所以请使用下面的代码

  var styleAttr = $("#divAddDetailPans").attr('style'); $("#divAddDetailPans").removeAttr('style'); $("#divAddDetailPans").attr('style', styleAttr.replace('top: 198px !important', 'top: 78px !important')); 
 $('#divL3.myclass').attr('style', 'height:0px !important'); 

会像以上那样工作吗?

你能试试这个方法,

   

jQuery的:

  $('#divL3').removeClass('myclass').addClass('newclass'); 

如果你希望稍后覆盖它,我不明白为什么你有CSS!重要的CSS。 删除CSS高度中的!important。 CSS始终优先于CSS标记样式。

  .myclass{ height:50px; } $('#divL3.myclass').css('height', '0px'); 

这对设计更好。

我有同样的问题,所以我在css中设置了max-height,然后通过jQuery覆盖了高度:

CSS

 #elem{ max-height:30px !important; } 

jQuery

 $('#elem').height('30px !important'); 

例如,我更喜欢创建一个类并将其添加到特定的div中

这可以是内联的,也可以是外部CSS文件:

  

如果这是永远不会改变的事情,您可以手动将该类添加到该div:

 
sometext here

或者您可以使用jQuery在该页面的底部添加此脚本标记

  

您可以使用’style’选项,但建议这样做:

  var currentStyle = $('#divL3').attr('style'); $('#divL3').attr('style', currentStyle + ' width:500px !important;'); 

这样您就不会覆盖现有样式,以防第三方插件向页面添加任何动态样式,如果您使用的是像WordPress这样的CMS,这并不罕见。

我遇到了一个问题,我们允许用户为Kendo网格定义自己的字体大小,但是在设置了值之后,然后以任何方式操作网格,它都会重置字体大小。 所以我们实际上为样式标记定义了一个ID,并且每次都用适当的CSS改变了html。

在主页面的顶部,我们根据PHP会话变量或数据库中保存的内容设置字体大小。

 echo ""; 

然后为了更改它,我们执行以下jquery,其中font_size是新大小

 $( "#grid-style" ).html( "table { font-size: " + font_size + "px !important; }" ); 

你试过这个吗?

 $('#divL3.myclass').css('height', '0px !important');