【问题标题】:jQuery hide/show div onclick spanjQuery 隐藏/显示 div onclick 跨度
【发布时间】:2011-08-20 16:18:17
【问题描述】:

我正在尝试在一个项目中使用 jQuery,我在这里和那里收集了一些东西,但时不时地我遇到了麻烦。

在这个 jsFiddle 上你可以看到我在做什么:http://jsfiddle.net/YpeeR/17/

jQuery(document).ready(function() {
jQuery('.toggle_hide').hide();

jQuery("#background_absolute_content li span").css('cursor', 'pointer').click(function() {
    var $this = $(this);
    $('.toggle_hide').not($this.next("div")).fadeOut(200, function() {
        $this.next("div").fadeIn(200);
    });
});

});

我在一个 li 元素中隐藏了 4 个 div。当用户单击 div 所在的 li 元素内的 span 标签时,会显示 div,而其他 div 将被关闭。这工作正常,但我希望用户也能够切换当前的 div。

因此,当用户单击 li 元素中的跨度时,会显示隐藏的 div,而当用户再次单击同一跨度时,我希望 div 再次隐藏。

不幸的是,fadeToggle 似乎没有起到作用,正如您在此处看到的那样 http://jsfiddle.net/YpeeR/18/ ,但我似乎无法弄清楚为什么会这样......

【问题讨论】:

  • 我可以看出您了解 StackOverflow 的工作原理! '问题'... jsFiddle... 评论... 现在告诉我们... 接受答案有这么难吗?

标签: jquery class


【解决方案1】:

我放慢了速度以显示更改:http://jsfiddle.net/YpeeR/23/

jQuery(document).ready(function() {
    jQuery('.toggle_hide').hide();

    jQuery("#background_absolute_content li span").css('cursor', 'pointer').click(function() {
        var $this = $(this);
        $this.next("div").fadeToggle(200);
        $('.toggle_hide').not($this.next("div")).fadeOut(800);
    });
})

动画完成后,您为每个 div 调用了 3 次 $this.next("div").fadeIn(200);,而不是 $this.next。

【讨论】:

  • 哇,谢谢!成功了,伙计,这个 jQuery 很棒,但对错误修复有点讨厌,但今天学到了很多。
  • @Peter,没问题!乐意效劳。请阅读:meta.stackexchange.com/questions/16721/…
【解决方案2】:

这很奇怪,因为您将fadeToggle 放在其他div 的fadeOut 的回调中,因为还有其他三个div,所以调用了三次。所以每次点击它会切换三次,你会看到它闪烁一次。试试这个:

jQuery(document).ready(function() {
    jQuery('.toggle_hide').hide();

    jQuery("#background_absolute_content li span").css('cursor', 'pointer').click(function() {
        var $this = $(this);
        $('.toggle_hide').not($this.next("div")).fadeOut(200);
        $this.next("div").fadeToggle(200);
    });
});

http://jsfiddle.net/Paulpro/YpeeR/25/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-07
    • 2021-02-05
    • 1970-01-01
    • 2015-09-25
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多