【问题标题】:Toggeling jQuery hide/show切换 jQuery 隐藏/显示
【发布时间】:2012-10-22 09:33:49
【问题描述】:

我有一个导航,我正在使用 jQuery 幻灯片显示导航下的内容。当您单击不同的导航项时,我可以切换 div,但是当我单击相同的导航项将其关闭时,它只是将选项卡弹回关闭然后再次打开。我现在正在关闭它的 div 内有一个关闭按钮。

如何让 div 打开后关闭>

示例链接为here

我的jQuery如下:

(function ($) {
    $.fn.showHide = function (options) {

        //default vars for the plugin
        var defaults = {
            speed: 1000,
            easing: '',
            changeText: 0,
            showText: 'Show',
            hideText: 'Hide'

        };
        var options = $.extend(defaults, options);

        $(this).click(function () { 

             $('.toggleDiv').slideUp(options.speed, options.easing);    
             // this var stores which button you've clicked
             var toggleClick = $(this);
             // this reads the rel attribute of the button to determine which div id to toggle
             var toggleDiv = $(this).attr('rel');
             // here we toggle show/hide the correct div at the right speed and using which easing effect
             $(toggleDiv).slideToggle(options.speed, options.easing, function() {
             // this only fires once the animation is completed
             if(options.changeText==1){
             $(toggleDiv).is(":visible") ? toggleClick.text(options.hideText) : toggleClick.text(options.showText);
             }
              });

          return false;

        });

    };
})(jQuery);

我正在开火:

$(document).ready(function(){

    $('.show_hide').showHide({           
        speed: 300,  // speed you want the toggle to happen 
        easing: '',  // the animation effect you want. Remove this line if you dont want an effect and if you haven't included jQuery UI
        changeText: 0, // if you dont want the button text to change, set this to 0
        showText: 'View',// the button text to show when a div is closed
        hideText: 'Close' // the button text to show when a div is open
    }); 

});

【问题讨论】:

  • 如何检查单击的项目是否是当前打开的项目(添加/删除类)或使用is(":visible")。如果它只是隐藏它,否则其他向上/向下滑动的东西?

标签: jquery toggle show-hide


【解决方案1】:

好吧,您在点击时将所有 div 向上滑动,这意味着当前打开的 div 也会向上滑动。

$('.toggleDiv').slideUp(options.speed, options.easing);

我的建议是给打开的 div 一个像“is_open”这样的类,你可以删除它 当你打开另一个 div 时。您可以在执行任何其他逻辑之前检查点击类:

if($(this).hasClass('is_open')) return;

【讨论】:

  • 有人可以创建一个 jsfiddle 并给我一个工作示例,我还是迷路了
【解决方案2】:

只需添加一个类即可完成此操作,并避免使用 $('.toggleDiv') 选择器对所有 div 进行额外操作。

最简单的方法是检查 toggleDiv 是否可见。只需将类中的“显示”属性从无更改为阻塞即可。

使用简单的 $(this).addClass('opened_div');打开 div 并稍后将其删除。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-16
    • 1970-01-01
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多