页面加载时的CSS动画

时间:2015-05-06 21:12:11

标签: html css css-animations

为什么以下代码在页面加载时没有动画?

#error {
    opacity: 0 text-align: center;
    background-color: rgba(255, 0, 0, 0.4);
    border-radius: 10px;
    border: 4px solid rgba(255, 0, 0, 0.4);
    line-height: 1.5;
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box;
}
.animate {
    opacity: 1;
    transition: opacity 0.4s ease-in;
    -ms-transition: opacity 0.4s ease-in;
    -moz-transition: opacity 0.4s ease-in;
    -webkit-transition: opacity 0.4s ease-in;
}
<div id="error" class="animate">This is an error message!</div>

1 个答案:

答案 0 :(得分:3)

如果您想要动画,则无法同时应用这两种样式。

要完成此操作,您可以在页面加载后使用JavaScript应用opacity属性。

window.onload = function() {
    document.getElementById("error").style.opacity = 1;
}
#error {
    opacity: 0;
    text-align: center;
    background-color: rgba(255, 0, 0, 0.4);
    border-radius: 10px;
    border: 4px solid rgba(255, 0, 0, 0.4);
    line-height:1.5;
    -webkit-background-clip: padding-box; /* for Safari */
    background-clip: padding-box;
    transition: opacity 0.4s ease-in;
    -ms-transition: opacity 0.4s ease-in;
    -moz-transition: opacity 0.4s ease-in;
    -webkit-transition: opacity 0.4s ease-in;
}
<div id="error">This is an error message!</div>