首页 > 解决方案 > 带有控件的 jQuery 幻灯片显示相反的动作

问题描述

我有一个幻灯片动画,里面有一点我喜欢的 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

标签: jqueryanimation

解决方案


所以我想出了答案!

下面是这背后的逻辑:

//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


推荐阅读