【问题标题】:Deactivate "element.style" in css/html?在 css/html 中停用“element.style”?
【发布时间】:2016-06-23 13:11:56
【问题描述】:

我在 Chrome 开发者工具窗口的“样式”标签中看到了这段 css 代码:

element.style {
    height: auto;
    width: 100%;
    margin-top: -148px;
}

我想在我的 .css 文件中用这个 css 代码覆盖它:

.so-widget-sow-simple-masonry-simple-masonry-d75171398898 .sow-masonry-grid-item img {
    width: auto;
    height: 244px;
    margin-top: 0px;
    margin-left: auto;
    margin-right: auto; 
}

但是element.style 的样式定义已经存在。 我找不到 .js 这么快。 有人能帮我吗? 谢谢

【问题讨论】:

  • 尝试通过为值添加 !important 来覆盖首选项.. 但这是不可取的...
  • 好的,这行得通,但还有其他解决方案吗?
  • 您可以检查stackoverflow.com/questions/2465158/… 以删除特定的内联样式

标签: javascript html css siteorigin


【解决方案1】:

你总是可以选择:

.so-widget-sow-simple-masonry-simple-masonry-d75171398898 .sow-masonry-grid-item img {
width: auto !important;
height: 244px !important;
margin-top: 0px !important;
margin-left: auto;
margin-right: auto; 
}

重要样式会覆盖内联样式,除非内联样式也有 !important 子句(但这实际上很少见)。

【讨论】:

    【解决方案2】:

    当然,您可以删除元素上的style 属性:

    element.removeAttribute('style');
    

    如果 element.style 消失了,您的 CSS 文件的规则将可见。

    【讨论】:

      【解决方案3】:

      您可以在每个样式的末尾添加 !important。

      例如使用这个:

      height: 244px !important;
      

      而不是

      height: 244px;
      

      【讨论】:

        【解决方案4】:

        您在 chrome 开发者窗口中看到的 element style 是元素上的样式,这些样式写为 inline

        element.style {
         /*this all are the inline written styles*/
        }
        

        现在说到But with this codes the element.style is allready there,由于CSS 优先级,您无法覆盖样式。在这种情况下,规则是内联 CSS 比外部 CSS 具有更高的优先级

        那你能做什么??

        1. 你必须要么remove the inline css 写在哪里。这样你的外部 CSS 就会应用

        2. 如果由于某种原因无法修改内联 CSS,则唯一的选择是在外部 CSS 文件中使用 set the styles as !important。这里的人已经提到过这个解决方案,但并不总是推荐。

        3. 获取写在该元素上的所有内联 CSS,并在您的外部文件中创建一个新类,然后将其放在那里,现在将这个类名称赋予该元素。所以原始样式被应用回来。现在到了必须覆盖的新样式的重点。使用 2 个类时还有新的 CSS 优先级规则。 CSS rule which is read last (in the css file, not the order you put in the element) will have priority。因此,请确保将新的 CSS 规则放在刚刚创建的其他类下方,如上所述。

          • 如果您必须使用 2 个单独的文件来编写这 2 个类怎么办?然后是另一个 CSS 优先级规则。 The file that is placed last in the DOM will have the priority(记住不是文件加载到 DOM 时,而是关于文件在 DOM 中的放置位置)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-07-10
          • 2015-12-17
          • 2022-01-21
          • 2020-11-02
          • 1970-01-01
          • 2014-09-09
          • 2010-12-22
          相关资源
          最近更新 更多