html - 使用纯 CSS3 显示/隐藏出现的 div

标签 html css

我遇到了一个困扰我好几天的问题。

在 ASP.NET MVC4 元素中,我每次都在 _Layout View 中检查 ViewBag 是否有结果消息,如果有,我会为消息文本呈现一个 div。我想为这个 div 设置动画,使其在大约 3 秒内出现和消失。如果可能的话,我想用纯 CSS 来完成这项工作。

这是我的代码片段:

CSS:

#result-message-div {
margin: 50px 0px auto;
width: auto;
background-color: #ffa11f;
text-align: center;
font-size: small;
font-weight: bold;
-webkit-animation: resultMessageAnimation 3s;
}

@-webkit-keyframes resultMessageAnimation {
0% { height: 0%; }
15% { height: 100%; }
75% { height: 100%; }
100% { height: 0%; }
}

Razor :

@if (ViewBag.ResultMessage != null)
{
    <div id="result-message-div">
        @ViewBag.ResultMessage
    </div>
}

使用这段代码,div 确实出现了,但是没有动画发生并且它仍然可见。毕竟,我在正确的轨道上吗?

最佳答案

你很亲近!问题是您使用 100% 作为高度。基本上,这意味着 100% 的父级,默认情况下仅与其内容一样大(因此,这是一个先有鸡还是先有蛋的问题)。

如果您可以为消息框设置静态高度,我想您的代码应该可以正常工作。

#result-message-div {
    margin: 50px 0px auto;
    /* width: auto; // not necessary as 'auto' is the default value */
    background-color: #ffa11f;
    text-align: center;
    font-size: small;
    font-weight: bold;
    height: 0; /* this value will apply after animation is done  */
    overflow: hidden; /* important, or  text will always show */
    [-webkit-/-moz-]animation: resultMessageAnimation 3s;
}

@[-webkit-/-moz-]keyframes resultMessageAnimation {
    0% { height: 0; }
    15% { height: 20px; } /* note static px value instead of % */
    75% { height: 20px; }
    100% { height: 0; }
}

http://jsfiddle.net/NufRJ/1/

关于html - 使用纯 CSS3 显示/隐藏出现的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24157557/

相关文章:

javascript - Angular-Bootstrap Datepicker - 在选择另一个日期时突出显示今天的日期

html+css usemap 不起作用

c# - 作为内联 C# 添加页眉和页脚到电子邮件

java - 以编程方式验证 HTML 代码

javascript - 如何使用 jquery 从数据表中单击按钮来选择过滤结果

html - bootstrap 4 不显示文本

javascript - 需要帮助自定义 jQuery 水平菜单

css - 响应式电子邮件设计中的填充

css - 使用流体布局是否明智?

javascript - 使用 Javascript 在模态对话框中切换隐藏和显示