使用javascript无法覆盖!important

时间:2016-02-23 10:09:26

标签: javascript html css

我有一个div.innerDiv已在CSS文件中分配了height: 300px !important;。我既不能更改现有的CSS文件,也不能添加要覆盖的新类。由于样式为!important,因此只能inline覆盖!important样式。但它不会产生预期的效果。

参考演示here

更新: 我只需要内嵌样式。

HTML:

<div>
    <div class="innerDiv">
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
        survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
        software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
</div>

CSS:

.innerDiv {
  height: 300px !important;
  width: 150px;
  border: 1px solid;
}

JS:

function overrideHeight() {
    document.getElementsByClassName('innerDiv')[0].style.height = 400 + 'px !important';
}

overrideHeight();

4 个答案:

答案 0 :(得分:4)

将您的函数声明更改为:

function overrideHeight() {
  document.getElementsByClassName('innerDiv')[0].style = "height: 400px !important";
}

这应该有效。请参阅this fiddle

似乎!important关键字不允许包含在前一种语法中,即直接使用style.heightstyle属性的设置有效,但没有值。

您可能已经知道了。但是,万一你忘记了,你可以通过右击它来检查小提琴的结果,并修复一些不能正常工作的东西。

答案 1 :(得分:1)

马特的答案非常有效,但是这是另一个,它使用JS在文档的头部创建File.Create(path);标签:

&#13;
&#13;
<style>
&#13;
var styleTags = document.createElement('style');
styleTags.type = "text/css";
var styleText = document.createTextNode('.innerDiv { height: 400px !important; } ');
styleTags.appendChild(styleText);
document.getElementsByTagName('head')[0].appendChild(styleTags);
&#13;
.innerDiv {
  height: 300px !important;
  width: 150px;
  border: 1px solid;
}
&#13;
&#13;
&#13;

实现相同结果的另一种方式。

答案 2 :(得分:1)

在我的浏览器(iPad Safari)中,Matt的答案只有在修改为:

时才有效
function overrideHeight() {
document.getElementsByClassName('innerDiv')[0].style.cssText = "height: 400px !important";
}

因此可能值得关注跨浏览器的怪癖。

答案 3 :(得分:0)

另一种选择:

document.getElementsByClassName('innerDiv')[0] .style.setProperty(“height”,“400px”,“important”);