带有控件相反动作的jQuery幻灯片

时间:2019-02-20 12:19:59

标签: jquery animation

我有一个幻灯片动画,其中包含我喜欢的一小段jquery代码。当我按下下一步时,动画运行良好。但是,当我尝试使用prev做相反的操作时,在恢复之前我有一个重复的动作。

有什么主意我可以跳过吗?

$("#slideshow > div:gt(0)").hide();

$("#after").click(function() {
  $('#slideshow > div:first')
    .fadeOut(1000)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
});

$("#prev").click(function() {
  $('#slideshow > div:first')
    .appendTo('#slideshow')

    .fadeOut(1000)
    .prev()
    .fadeIn(1000)
    .end();

});

查看此处:https://codepen.io/1conu59/pen/bzJdzz

1 个答案:

答案 0 :(得分:0)

所以我想出了答案!

这是背后的逻辑:

//Comments explanation

$("#btnAfter").click(function() {

   // I select the first div, the one at the top
  $('#slideshow > div:first')

    // I put it at the end of the stack
    .appendTo('#slideshow')    
});

// Here is the opposite logic
$("#btnPrev").click(function() {

  // Here I select the last div, the one at the bottom
  $('#slideshow > div:last')

    //I put it at the top of the stack which also move the dom selection with it
    .prependTo('#slideshow')        
});

结果是:https://codepen.io/1conu59/pen/gqJPjP

这创建了一个非常清晰的DOM操作思维逻辑,类似于将一堆纸牌混在一起。

这是一些资源,可以帮助我很多:

https://www.elated.com/articles/jquery-adding-elements/

https://www.w3schools.com/jquery/jquery_ref_traversing.asp