我有一个 Greasemonkey 脚本,它使用 .css()
或 GM_addStyle()
应用样式。这些样式将被页面上的样式覆盖,从而导致不良影响。
我知道我可以通过在所有样式上使用 !important
来解决这个问题,但我真的不想这样做。有什么方法可以不使用 !important
来做到这一点吗?
最佳答案
在 Greasemonkey 脚本和 Stylish 样式中使用 !important
没有错。 (它有时在常规网页中被误用,但用户脚本不同)。
!important
是覆盖属性中设置的样式的唯一方法。例如,如果我们想改变这个:
<div id="annoyingBlock" style="background: red; top: 4em; display: inline block ... Bunch of other styles that we don't want to touch.">
Look at me!
</div>
要有白色背景,我们的用户脚本必须覆盖 style
属性(这在大型复杂站点上可能是一个正确的痛苦,并且可能破坏我们可能仍然想要的其他内联样式)或者,它必须使用 !important
标志,如下所示:
GM_addStyle ( " \
#annoyingBlock { \
background: white !important; \
} \
" );
这是因为 attributes (inline styles) have a higher precedence除了 !important
样式。
如果您使用 .css()
更改的样式被页面的 javascript 覆盖,请使用 this answer 中的技术。来解决这个问题。
关于javascript - 如何在 Greasemonkey 脚本中不使用 !important 覆盖页面样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15078364/