如何在定义的时间后在一个div中淡出和淡出元素?

时间:2013-11-23 17:53:28

标签: javascript jquery

如何在同一个div中一个接一个地显示排队的消息?目前的解决方案很糟糕,因为它会立即显示新的div。

HTML:

<div id="alert-bar-container"></div>
<button id="show">First message</button>
<button id="next">Next message</button>

JavaScript的:

var timeout;
$("#show").click(function () {
    alertBar("this appears first");
});
$("#next").click(function () {
    alertBar("this should wait and show after first disappeared");
});
function alertBar(msg) {
    var message_span = $('<span />').html(msg);
    var wrap_bar = $('<div />').addClass('alert_bar');
    $('#alert-bar-container').html(wrap_bar.append(message_span).hide());
    clearTimeout(wrap_bar.data("timer"));
    wrap_bar.clearQueue();
    if (wrap_bar.filter(":hidden").length == 1) wrap_bar.fadeIn('fast');
    wrap_bar.data("timer", setTimeout(function () {
        wrap_bar.fadeOut("slow");
        wrap_bar.remove();
    }, 2500));
}

示例:http://jsfiddle.net/LsRK8/

2 个答案:

答案 0 :(得分:1)

希望这有帮助......没有按钮编辑......

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>delay demo</title>
<style>
div {
position: absolute;
width: 60px;
height: 60px;
float: left;
}
.first {
background-color: #3f3;
left: 0;
}
.second {
background-color: #33f;
left: 80px;
}
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body> 
<div class="first"></div>
<div class="second"></div>
<script>
$( document ).ready(function() {
$( "div.first" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );
$( "div.second" ).slideUp( 300 ).fadeIn( 400 );
});
</script>
</body>
</html>

答案 1 :(得分:1)

尝试:

HTML:

<div id="container">
    <div class="msg active">first</div>
    <div class="msg">second</div>
    <div class="msg">third</div>
    <div class="msg">fourth</div>
</div>

JS:

setInterval(function(){
    var active = $("#container").find(".active");
    var i = $(active).index();
    var len = $("#container").find(".msg").length;
    var next;
    if(i == (len-1)){
        next = $("#container").find(".msg:first");
    }
    else{
        next = $("#container").find(".msg:eq("+(i+1)+")");
    }
    $(active).removeClass("active").hide();
    $(next).addClass("active").fadeIn();
},3000);

Fiddle here.