【问题标题】:How to override CSS transitions for particular elements?如何覆盖特定元素的 CSS 过渡?
【发布时间】:2015-09-17 23:26:23
【问题描述】:

我想知道是否有一种快速/智能的方法来覆盖 HTML 文档中特定元素的 CSS 过渡?

如果我们有这个 CSS 定义设置,它将对所有元素应用过渡:

* {
    transition: all 0.35s ease-in-out;
}

如何覆盖文本元素的 CSS 过渡效果,以便所有文本都不会应用过渡效果?请注意,这涵盖了所有元素,例如 p、h1、h2、h3、h4、h5、h6 等,以及包含文本的元素,例如我是一些怪异的文本。

以下代码 sn-p 是不应发生的示例。背景颜色更改过渡是预期发生的,但文本不应过渡。

* {
  transition: all 0.35s ease-in-out;
}

.egodiv {
  font-size: 12px;
  color: black;
  background-color: white;
}

.egodiv:hover {
  font-size: 20px;
  color: white;
  background-color: red;
}
<!DOCTYPE html>
<html>
  <body>
    <div class="egodiv">Look at me now!</div>
  </body>
</html>

【问题讨论】:

  • 坦率地说,transition:all 一切都很混乱。当不需要它时,您将花费更多的时间将其关闭,而不是在您想要的元素上定义它。另外,我认为您可能会遇到一些性能和布局问题。

标签: css css-transitions


【解决方案1】:

关闭特定样式的过渡的唯一方法是完全重新定义过渡属性。只要您知道原始转换值就可以了:

* {
  transition: all 0.35s ease-in-out;
}

.egodiv {
  font-size: 12px;
  color: black;
  background-color: white;
  transition: all 0.35s ease-in-out, font-size .01s linear;
}

.egodiv:hover {
  font-size: 20px;
  color: white;
  background-color: red;
}
&lt;div class="egodiv"&gt;Look at me now!&lt;/div&gt;

我以为是您想要禁用转换的font-size

【讨论】:

    【解决方案2】:

    试试这个:

    * {
      transition: all 0.35s ease-in-out;
    }
    
    .egodiv {
      font-size: 12px;
      color: black;
      background-color: white;
      transition:none; // override transition
    }
    
    .egodiv:hover {
      font-size: 20px;
      color: white;
      background-color: red;
    }
    <!DOCTYPE html>
    <html>
      <body>
        <div class="egodiv">Look at me now!</div>
      </body>
    </html>

    【讨论】:

    • 他想覆盖最好用transition:none !important;
    • @Alaeddine 不,不是。在完全不必要的地方使用 !important 正是您不应该建议的。
    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-05-29
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    • 2018-05-20
    相关资源
    最近更新 更多