CSS 转换 属性 应该去哪里?

Where should the CSS transition property go?

在为元素创建 CSS 转换时,transition 属性 应该应用于元素的现有 class(或 ID 或选择器)还是新 class 导致转换?我认为它以任何一种方式工作,但一种方式比另一种方式更好,为什么?

JSFiddle

.box {
    height: 100px;
    width: 100px;
    background: blue;
}

/* background-change class to be added to the element with the box class */
.background-change {
    background: red;
    /* Should this be under .background-change or .box? */
    transition: background 2s;
}

应适用于原文class。最终结果(在本例中为背景值)应应用于新的 class.

过渡 属性 不会初始化过渡,它只是告诉元素任何差异都会有该过渡。

我推荐这篇文章以进行更深入的阅读:http://alistapart.com/article/understanding-css3-transitions

应该是这样的:

.box {
  height: 100px;
  width: 100px;
  background: blue;
  transition: background 2s; 
}

.background-change {
  background: red;     
}

您可以使用这两种变体,它们都可以。但是你应该明白它们之间的区别。

如果您将 transition 属性 设置为 new/separate class,您的过渡将仅在您设置 class:

JSFiddle

$('.box').hover(function() {
    $(this).toggleClass('background-change');
});
.box {
    height: 200px;
    width: 200px;
    background: green;
}

.background-change {
    background: red;
    transition: background 2s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div class="box">Hover it to change background</div>

但是如果您将 transition 属性 设置为 main/existing class,当您删除 class:

时,您的过渡也会应用]

JSFiddle

$('.box').hover(function() {
    $(this).toggleClass('background-change');
});
.box {
    height: 200px;
    width: 200px;
    background: green;
    transition: background 2s;
}

.background-change {
    background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div class="box">Hover it to change background</div>

我更喜欢使用最后一个变体,因为它看起来更好而且更一致。