如何使用jQuery使用!important覆盖内联样式? [英] How to override inline styles with !important using jquery?

查看:271
本文介绍了如何使用jQuery使用!important覆盖内联样式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个:

<p style="color:red !important;">sample text here</p>

然后我想在JQuery中覆盖该样式,我该怎么做?

and then I want to override that style in JQuery, how would I do it?

在CSS中使用!important显然不起作用(但还是尝试了). 我在想是否可以做类似的事情:

using !important in CSS obviously doesn't work(but tried it anyway). I'm thinking if I can do something like:

$(document).ready(function(){
  $('p').css("color","#fff");
});

对此有何想法?

推荐答案

您的代码是正确的,您可以按照建议的方式进行操作.即使元素上已经有一个内联样式规则,但是一旦文档准备就绪,它将用您编写的内容替换该规则,

Your code is correct, you can do it exactly like you suggested. Even though there is an inline style rule already on the element, once the document is ready, it will replace that rule with what you've written, see here.

演示

DEMO

如果出于某些原因,您需要更多的保证,则可以在应用 removeAttr() jquery方法(但这有点浪费代码).

If for some reason, you want more assurance, you can clear the inline styling before you apply the new styling with the removeAttr() jquery method (but it's a bit of a waste of code).

演示

DEMO

$(document).ready(function(){
	$('p').removeAttr('style');
  $('p').css("color","blue");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<p style="color:red !important;">sample text here</p>

这篇关于如何使用jQuery使用!important覆盖内联样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆