【问题标题】:Is it possible to accumulate CSS transitions rather than overwrite them?是否可以累积 CSS 过渡而不是覆盖它们?
【发布时间】:2020-11-02 05:30:58
【问题描述】:

我想知道是否有一种方法可以累积 CSS 过渡而不是在应用于单个类时覆盖它们。例如,我有两个实用程序类.btn.shadow,它们可以独立工作:

/* .btn utility class */
.btn {
  padding: 10px 20px;
  border: 1px solid darkblue;
  color: white;
  background-color: #4fb0e8;
  text-transform: uppercase;
  cursor: pointer;
  outline: none;
  border-radius: 7px;
  
  transition: background-color 0.8s; /* transition #1 */
}

.btn:hover {
  background-color: #4f8ce8; /* this should always transition */
  font-size: 15px; /* this should never transition */
}

/* .shadow utility class */
.shadow {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: box-shadow 0.8s; /* transition #2 */
}

.shadow:hover {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.5);
}
<button class="btn">Button 1</button>

<div class="shadow">
  <h2>I div with a shadow</h2>
</div>

<button class="btn shadow">Button 2</button>

如您所见,当您将鼠标悬停在按钮上时,其颜色会发生变化,而当您将鼠标悬停在 div 上时,其阴影也会发生变化。这是预期的行为。

问题是,当我将这两个类(如最后一个标记为 Button 2 的按钮所示)组合在一起时,背景颜色转换被框阴影转换覆盖,因此框的背景颜色不再转换。最好当一起应用时,我能够以某种方式“累积”两个类的过渡效果。有没有一种简单的方法可以用 CSS 做到这一点,还是我必须手动组合并将阴影过渡添加到我的按钮类?

【问题讨论】:

  • 不,您不能以这种方式组合它们。每个堆叠的类将根据它们在 CSS 中定义的顺序(而不是它们写入元素上的类列表的顺序)覆盖前一个的属性。如果你想要两者,你需要创建一个像 .btn-shadow 这样的新类,它会定义像 transition: box-shadow 0.8s, background-color 0.8stransition: all 0.8s;

标签: html css css-transitions


【解决方案1】:

.shadow 的转换从transition: box-shadow 0.8s; 更改为transition: box-shadow 0.8s, background-color 0.8s;

【讨论】:

    猜你喜欢
    • 2020-02-22
    • 2020-01-17
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    相关资源
    最近更新 更多