CSS过渡属性应该去哪里?

时间:2015-07-07 16:23:17

标签: css css3 css-transitions

为元素创建CSS转换时,transition属性是应该应用于元素的现有类(或id或选择器)还是应用于导致转换的新类?它的工作方式我相信,但是比其他方式更好,为什么?

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;
}

3 个答案:

答案 0 :(得分:0)

应该应用于原始类。最终结果(在本例中为背景值)应该应用于新类中。

transition属性不会初始化转换,它只是告诉元素任何差异都会有转换。

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

答案 1 :(得分:0)

应该是这样的:

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

.background-change {
  background: red;     
}

答案 2 :(得分:0)

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

如果您将transition属性设置为新/单独的类,则只有在设置此类时才会应用转换:

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>
&#13;
&#13;
&#13;

但是如果您将transition属性设置为main / existing class,则在删除class时也会应用转换:

JSFiddle

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

.background-change {
    background: red;
}
&#13;
<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>
&#13;
&#13;
&#13;

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