4

所以我正在构建一个非常简单的带有 4 个 div 的轮播。它使用 2 个 jQuery 函数将 div 设置为第一个或最后一个位置。只有 alpha 转换,因为我不需要移动。

出于某种原因,虽然我可以使用 .eg(n) 等访问我的 div,但第一个、最后一个和其他各种数字在此函数中不起作用。

代码:

$('#prev').click(function() {

    $('.container .divname').animate({opacity: 0}, 1000,function(){ 

     $('.container .divname:first').before($('.container .divname:last')); 

     $('.container .divname').animate({opacity: 1}, 1000); 

    });

    return false;

});

所以这个功能不起作用。

$('#prev').click(function() {

        $('.container .divname').animate({opacity: 0}, 1000,function(){ 

         $('.container .divname:eq(0)').before($('.container .divname:eq(3)')); 

         $('.container .divname').animate({opacity: 1}, 1000); 

        });

        return false;

    });

这也不起作用,但是如果我将eq(3)更改为eq(2)它可以,但显然错过了我的一个 div。我仍然可以访问 eq(3),因为我对其进行了测试,并将其设置为红色背景。

$('.container .divname:eq(3)').css({'background-color' : '#ff0000'});

这有效...

谁能告诉我为什么会发生这种情况?

html示例如下

<html>
     <div class="container">
          <div class="divname">
               <p>some content</p>
          </div>
          <div class="divname">
               <p>some content</p>
          </div>
          <div class="divname">
               <p>some content</p>
          </div>
          <div class="divname">
               <p>some content</p>
          </div>
     </div>
</html>

编辑:

我已经为观众中的 w3c 孩子们将所有 id 更改为 class。问题仍然存在。

http://jsfiddle.net/3P8t5/1/

4

2 回答 2

2

您的问题的根源是您已将 .before() 函数用于在附加到四个 div 的回调函数中移动 div - 因此它被称为四次,这意味着所有内容都被移动了四次,使您回到第一方.. .并且因为它是一个如此简单的小循环,它很快而且似乎什么也没发生。

解决方案 - 仅将动画功能附加到容器;

$('#prev').click(function() {

// Fade just the container - not each placeholder meaning the callback function is only called once, not four times
$('.container').animate({
    opacity: 0
}, 1000, function() {

    $('.container .divname:eq(0)').before($('.container .divname:eq(3)'));

    // Fade back in just the container - not each placeholder
    $('.container').animate({
        opacity: 1
    }, 1000);
});
return false;
});​

http://jsfiddle.net/cywjs/1/

于 2012-11-24T20:49:33.840 回答
0

除了朋友建议(ID 应该是唯一的)之外,我在您的代码中看到拼写错误。在 div 标签中更改"divnaname"为。例如:"divname"<div id="divnaname"> ... <div>

编辑:

检查这个演示演示

这是你想要做的吗?

于 2012-11-23T19:04:09.083 回答