2012-01-18 77 views
0

我在jQuery/JavaScript中有一个展开和折叠系统设置。一旦你点击DIV,DIV中的图像就会改变它的状态。但是,当您似乎再次单击该DIV时,图像不会返回到原始状态。它陷入了另一种状态。图像返回原始来源OnClick?

注意:我在同一页面上的多个实例中创建了一个手风琴效果的脚本,当您单击不同的“ITEM”时,图像返回到先前选择的DIV的原始状态。

这里是的jsfiddle:http://jsfiddle.net/4Dtd8/

太谢谢你了!

+0

上的代码只是一个评论,你会发现它更容易阅读,如果您更换'和'$'jQuery'。至少它更容易遵循我(做了很多jQuery,实际上看到这些词让我分心)。 – Kekoa 2012-01-18 17:34:17

+0

@Kekoa:如果我用美元符号($)开始所有的jQuery语句,那么冲突发生和错误的空间会更多。我会建议在每个语句之前使用jQuery。 – 2012-01-18 17:40:37

+0

除非加载另一个库,例如使用'$'的原型,否则您应该没有冲突。 http://docs.jquery.com/Using_jQuery_with_Other_Libraries – Kekoa 2012-01-18 18:18:24

回答

1

使用CSS放置图像中的h1标签的背景。然后,你可以从.open.closed切换类的项目,让CSS手柄改变图像。

jQuery('.item .expandacc').click(function() { 
    jQuery('.item .expandacc').not(this).removeClass("open").addClass("closed") 
     .siblings('.contentacc').slideUp('normal'); 
    jQuery(this).next('.contentacc').slideToggle('normal'); 
    jQuery(this).toggleClass("closed").toggleClass("open"); 
}); 

http://jsfiddle.net/petersendidit/4Dtd8/9/

1

它停留在备用状态的原因是该行:

jQuery(this).find('img').attr('src','http://www.jornal.us/icons/expandIcon.jpg'); 

不管是什么状态时,它应该中,这是最后的代码,影响图像的源。因此,源始终设置为该行中指定的内容。

+0

所以你建议我如何解决这个问题?在选择了不同的DIV CLASS后,要让图像返回到原始状态,但在选择该类时仍然保持图像处于备用状态?谢谢! – 2012-01-18 17:39:49

2

您可以监视内容的可见性以确定应显示哪个图标。

http://jsfiddle.net/4Dtd8/7/

jQuery('.item .expandacc').click(function() { 
    if (jQuery($(this).next('.contentacc').is(':visible')) { 
     jQuery('.expandacc h1 img').attr('src', 'http://www.novell.com/documentation/extend52/Docs/help/exteNd/books/GTRImages/expandIcon.png'); 
    } 
    else { 
     jQuery(this).find('img').attr('src', 'http://www.jornal.us/icons/expandIcon.jpg'); 
    } 
    jQuery('.item .expandacc').not(this).siblings('.contentacc').slideUp('normal'); 
    jQuery(this).siblings('.contentacc').slideToggle('normal'); 
}); 
+0

但是有了多个课程,我将如何实现我所拍摄的内容?例如:http://jsfiddle.net/4Dtd8/6/ – 2012-01-18 17:51:40

+0

另外,我认为.is(':visible')将因为幻灯片动画而始终为真。 http://jsfiddle.net/skram/4Dtd8/8/ – 2012-01-18 17:53:20

+1

@AaronBrewer - 使用'next',以便它只检查下一个内容块。 HTTP://的jsfiddle。net/4Dtd8/7/ – mrtsherman 2012-01-18 17:53:26

1

我添加了一个自定义的ATTR isExpanded的图像标签保存,如果它展开或折叠,并检查了价值发现它的状态。

DEMO这里

的jQuery( '项目.expandacc。 ')点击(函数(){
的jQuery(这).siblings()的slideToggle( '正常')。' contentacc。';

var $img = jQuery(this).find('img'); 
    var isExpanded = $img.attr('isExpanded'); 

    // For some browsers, `isExpanded` is undefined; for others, 
    // `isExpanded` is false. Check for both. 
    if (typeof isExpanded === 'undefined' || 
      isExpanded === false || 
       isExpanded == 'true') { 
     $img.attr('src', 'http://www.jornal.us/icons/expandIcon.jpg'); 

     $img.attr('isExpanded', 'false'); 
    } else { 
     $img.attr('src', 'http://www.novell.com/documentation/extend52/Docs/help/exteNd/books/GTRImages/expandIcon.png'); 

     $img.attr('isExpanded', 'true'); 
    }