【问题标题】:Automatically toggle between two divs在两个 div 之间自动切换
【发布时间】:2012-04-21 00:46:51
【问题描述】:

我有两个 div 嵌套在一个包含的 div 中,并希望在两个 div 之间不断切换。

  <div style="position: relative; top: 50px; width: 778px; margin: 0 auto;">
    <div id="alerts" style="float: right; width:200px; height: 25px; background: goldenrod; border-radius: 3px 3px 3px 3px; font: 11px Arial; color: #404040; overflow: hidden;"> 
      <div id="Mass_alert" class="alert" style="position: relative; top: 0px; margin: 0 auto; text-align: center;"></div>
      <div id="Devotion_alert" class="alert" style="position: relative; top: 20px; margin: 0 auto; margin-top: 10px; text-align: center;"></div>
    </div>
  </div>

$('#alerts').ready(function(){
    $('#Mass_alert').ready(function(){
    fadein_Mass();
    });
});

function fadein_Mass() {
    $('#Devotion_alert').fadeOut(600, function() {
    $('#Mass_alert').fadeIn(600);
    fadein_Devotion();
    });
}

function fadein_Devotion() {
    $('#Mass_alert').fadeOut(600, function() {
    $('#Devotion_alert').fadeIn(600);
    fadein_Mass();
    });
}

我希望能够通过淡入淡出效果做到这一点:淡入淡出Mass_alert,淡入淡出Devotion_alert。最好的方法是什么?

编辑 *这行得通*

  <div style="position: relative; top: 0px; width: 778px; margin: 0 auto;"> 
    <div id="alerts" style="float: right; width:260px; height: 25px; background: goldenrod; border-radius: 3px 3px 3px 3px; font: 11px Arial; color: #101010;">
      <div id="Mass_alert" class="alert" style="position: relative; top: 3px; margin: 0 auto; text-align: center; width:100%; height: 20px;">Mass alert</div>
      <div id="Devotion_alert" class="alert" style="position: relative; top: -17px; margin: 0 auto; text-align: center; width:100%; height: 20px;">devotion alert</div>
    </div>
  </div>

$(document).ready(function() {  
    var continuous = function () {
    $("#Mass_alert").fadeToggle(6000, 'swing');
    $("#Devotion_alert").fadeToggle(6000, 'swing');   
    };
    $("#Devotion_alert").hide();
    setInterval(continuous,600); 
});

【问题讨论】:

    标签: javascript css animation jquery-animate fade


    【解决方案1】:

    如果您使用 jQuery,您可以执行以下操作:

    $('#Mass_alert').toggle(100);
    $('#Devotion_alert').toggle(100);
    

    这是假设其中一个 div 最初是隐藏的。传递给 toggle 的参数是过渡效果的持续时间。

    【讨论】:

    • 当您使用它时,不要通过放置内联样式来浪费类的使用。这是非常混乱和不专业的,并增加了您的页面加载。最好将样式放置在样式表中它们所属的位置。您可以在单个元素上拥有多个类,因此具有
      是完全有效且更简洁的。
    • @Joe 如果我想要一个淡入淡出效果,这可以通过编辑中的代码来实现吗?
    • 如果您指的是 Lazerblade 的编辑,那么是的,您如何选择元素并不重要,只要您使用持续时间参数调用 toggle()。
    • 如果我只把你建议的切换代码和Devotion_alert 隐藏起来,然后Mass_alert 快速闪烁,那么包含的 div 是空白的。
    【解决方案2】:
    var continuous = function() {
        $("#Mass_alert").fadeToggle(600);
        $("#Devotion_alert").fadeToggle(600);   
    }
    
    setInterval(continuous,600);
    

    这将每 600 毫秒连续发生一次。

    【讨论】:

    • 这几乎可以工作,但只显示Mass_alert。第二个 div Devotion_alert 未显示。
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签