如何在页面加载

时间:2017-04-11 12:16:59

标签: javascript jquery html css

嗨我想在页面加载后在我的页面上显示小吃栏而不点击任何内容。我有一段代码,但它在onclick上工作。但我想在页面加载后没有任何单击显示消息。

function snackBar() {
    var x = document.getElementById("snackbar")
    x.className = "show";
    setTimeout(function(){ x.className = x.className.replace("show", ""); }, 3000);
}
#snackbar {
    visibility: hidden;
    min-width: 250px;
    margin-left: -125px;
    background-color: #333;
    color: #fff;
    text-align: center;
    border-radius: 2px;
    padding: 16px;
    position: fixed;
    z-index: 1;
    right:0;
    bottom: 30px;
    font-size: 17px;
}

#snackbar.show {
    visibility: visible;
    -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
    animation: fadein 0.5s, fadeout 0.5s 2.5s;
}

@-webkit-keyframes fadein {
    from {bottom: 0; opacity: 0;} 
    to {bottom: 30px; opacity: 1;}
}

@keyframes fadein {
    from {bottom: 0; opacity: 0;}
    to {bottom: 30px; opacity: 1;}
}

@-webkit-keyframes fadeout {
    from {bottom: 30px; opacity: 1;} 
    to {bottom: 0; opacity: 0;}
}

@keyframes fadeout {
    from {bottom: 30px; opacity: 1;}
    to {bottom: 0; opacity: 0;}
}
<button onclick="snackBar()">Show Snackbar</button>

<div id="snackbar">Some text some message..</div>

3 个答案:

答案 0 :(得分:1)

试试这个javascript:

<body onload="snackBar()">

如果您使用的是jquery,那么您也可以尝试这个:

$( document ).ready(function() {
    snackBar();
});

希望这对你有用..谢谢!

答案 1 :(得分:0)

我认为不是onclick而是$(document).ready(function(){ snackBar(); });

答案 2 :(得分:0)

 $(document).ready(function() {
 setTimeout(function(){ 
        var x = document.getElementById("snackbar");
        x.className = "show";
        setTimeout(function(){ x.className = x.className.replace("show", ""); }, 1000);
       }, 2000)
    });
 #snackbar {
        visibility: hidden;
        min-width: 250px;
        margin-left: -125px;
        background-color: #333;
        color: #fff;
        text-align: center;
        border-radius: 2px;
        padding: 16px;
        position: fixed;
        z-index: 1;
        right:0;
        bottom: 30px;
        font-size: 17px;
    }

    #snackbar.show {
        visibility: visible;
        -webkit-animation: fadein 0.5s, fadeout 0.5s 2.5s;
        animation: fadein 0.5s, fadeout 0.5s 2.5s;
    }

    @-webkit-keyframes fadein {
        from {bottom: 0; opacity: 0;} 
        to {bottom: 30px; opacity: 1;}
    }

    @keyframes fadein {
        from {bottom: 0; opacity: 0;}
        to {bottom: 30px; opacity: 1;}
    }

    @-webkit-keyframes fadeout {
        from {bottom: 30px; opacity: 1;} 
        to {bottom: 0; opacity: 0;}
    }

    @keyframes fadeout {
        from {bottom: 30px; opacity: 1;}
        to {bottom: 0; opacity: 0;}
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="snackBar()">Show Snackbar</button>

    <div id="snackbar">Some text some message..</div>

嗨!这个演示将向您展示小吃吧,没有任何点击只有DOM加载,你也可以设置窗口加载后小吃栏的时间,只要你想显示2000 = 2秒