如何在页面加载时自动显示/隐藏Divs?

时间:2020-10-29 02:58:45

标签: javascript jquery

我正在尝试创建一些客户推荐的幻灯片。在页面加载时,我想每隔几秒钟显示/隐藏下一个推荐。我有示例工作,但仅使用单击方法。也许有人可以指出如何无需点击即可完成这项工作,而是在页面加载时自动完成?

我尝试将.click替换为.ready / .load,但没有任何反应。

$(function(){
 $("button").click(function(){
        $(this).parent().fadeOut(500).next().delay(500).fadeIn(500);
    });
});
section {
    width: 300px;
    height: 250px;
    background-color: #ADD3C9;
    margin: auto;
    display: flex;
    flex-direction: column;
}
button {
    display: block;
    margin-top: auto;
    margin-right: auto;
    margin-left: auto;
    font-size: 2em;
    padding: 10px;
    margin-bottom: 10px;
}
#p2,#p3,#p4 {display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="p1">
    <div>Content for  class "1" Goes Here</div>
  <button>Next</button>
</section>

<section id="p2">
    <div>Content for  class "2" Goes Here</div>
  <button>Next</button>
</section>

<section id="p3">
  <div>Content for  class "3" Goes Here</div>
  <button>Next</button>
</section>

<section id="p4">
  <div>Content for  class "4" Goes Here</div>
</section>

1 个答案:

答案 0 :(得分:2)

$(function(){
  setInterval(function() {
        $('section:not(#p4)[style*="display: flex"]').fadeOut(500).next().delay(500).fadeIn(500);
  }, 1000);
});
section {
    width: 300px;
    height: 250px;
    background-color: #ADD3C9;
    margin: auto;
    display: flex;
    flex-direction: column;
}
button {
    display: block;
    margin-top: auto;
    margin-right: auto;
    margin-left: auto;
    font-size: 2em;
    padding: 10px;
    margin-bottom: 10px;
}
#p2,#p3,#p4 {display:none;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="p1" style="display: flex;">
    <div>Content for  class "1" Goes Here</div>
  <button>Next</button>
</section>

<section id="p2">
    <div>Content for  class "2" Goes Here</div>
  <button>Next</button>
</section>

<section id="p3">
  <div>Content for  class "3" Goes Here</div>
  <button>Next</button>
</section>

<section id="p4">
  <div>Content for  class "4" Goes Here</div>
</section>