【问题标题】:Showing a bootstrap alert message for a specific time in html and css在 html 和 css 中显示特定时间的引导警报消息
【发布时间】:2017-10-29 08:04:04
【问题描述】:

我在下面有这个元素,它在屏幕上显示成功/失败横幅。 有没有办法可以在 html/css 中设置它在 4 秒后隐藏?

<div id=mainAlertMessage class="alert @message.CssClassName alert-dismissible" role="alert">
  <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
  <div style="text-align: center"><strong>@message.Title</strong> @message.Message</div>
</div>

我通过像这样在我的控制器中设置 tempData 来显示它

TempData["UserMessage"] = new BannerMessage() { CssClassName = "alert-success", Title = "Success!", Message = "Notification settings were updated!" };

【问题讨论】:

    标签: html css asp.net-mvc twitter-bootstrap


    【解决方案1】:

    您可以使用 CSS 动画和关键帧来完成您想要的结果。

        .alert {
            animation: autoHide 0s ease-in 4s forwards;
        }
    
        @keyframes autoHide {
            to {
                width:0;
                height:0;
                overflow:hidden;
            }
    <div id=mainAlertMessage class="alert @message.CssClassName alert-dismissible" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div style="text-align: center"><strong>@message.Title</strong> @message.Message</div>
    </div>

    【讨论】:

    • 不用担心,CSS 已经走过了漫长的道路。
    • 哇,我也从未想过使用关键帧。很好的答案@BramG
    【解决方案2】:

    您可以在文档就绪事件上使用 javascript setTimeout 函数。假设页面中包含 jQuery,

    $(function () { 
        var duration = 4000; // 4 seconds
        setTimeout(function () { $('#mainAlertMessage').hide(); }, duration);
    });
    

    您不一定需要 jquery,使用 vanilla javascript,您可以在 onload event 中连接代码

    window.onload = function() {
        var duration = 2000; //2 seconds
        setTimeout(function () { $('#mainAlertMessage').hide(); }, duration);
    };
    

    【讨论】:

    • 这不值得反对。 @shyju 明确指出,如果没有 JS,不可能 并提供了替代方案
    • 嗯,那么可以在html中内联js吗?这不是我最初问的问题
    • 你的意思是在html中内联js。您可以在页面的脚本标记内包含我在答案中的 js 代码。
    • 你可以创建一个内联触发的函数吗? &lt;button onclick="myFunction()"&gt;&lt;/button&gt;然后在别处定义您的setTimeout,但这与您将得到的一样接近。此外,您应该接受给出的答案。
    • 是的。您可以将 setTimeout 调用放在您的 myFunction 定义中,并且可以在按钮单击中调用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-05
    • 1970-01-01
    • 2022-11-07
    • 1970-01-01
    相关资源
    最近更新 更多