jQuery搜索切换

时间:2015-04-04 11:42:26

标签: javascript jquery html css

在我的网站上我有一个div .toggle-search,如果点击它,它会扩展为.search-expand搜索表单所在的位置。这是jQuery中的代码

/*  Toggle header search
/* ------------------------------------ */
    $('.toggle-search').click(function(){
        $('.toggle-search').toggleClass('active');
        $('.search-expand').fadeToggle(250);
            setTimeout(function(){
                $('.search-expand input').focus();
            }, 300);
    });

现在关闭.search-expand的唯一方法是再次点击.toggle-search。但是如果你点击网站上的任何其他地方,我想改变它关闭。为了一个更简单的例子,我有Hueman主题,我正在谈论右上角的搜索选项。 http://demo.alxmedia.se/hueman/

谢谢!

4 个答案:

答案 0 :(得分:3)

在搜索区域以外的所有元素上添加事件。

$('body *:not(".search-expand")').click(function(){
    $('.toggle-search').removeClass('active');
    $('.search-expand').fadeOut(250);
});

或其他方式,

$('body').click(function(e){
    if(e.target.className.indexOf('search-expand') < 0){
        $('.toggle-search').removeClass('active');
        $('.search-expand').fadeOut(250); 
    }
});

答案 1 :(得分:1)

您可以在主窗口中添加一个删除活动类的单击处理程序:

$(window).click(function(){
  $('.toggle-search').removeClass('active');
}

然后在点击切换搜索元素内部时阻止删除类

$('.toggle-search').click(function(e){
  e.stopPropagation();
  // remainder of click code here

)};

答案 2 :(得分:1)

var isSearchFieldOpen = false;
var $toggleSearch = $('.toggle-search');
var $searchExpand = $('.search-expand');

function toggleSearch() {
    // Reverse state
    isSearchFieldOpen = !isSearchFieldOpen;

    $toggleSearch.toggleClass('active');
    // You can use callback function instead of using setTimeout
    $searchExpand.fadeToggle(250, function() {
        if (isSearchFieldOpen) {
            $searchExpand.find('input').focus();
        }
    });
}

$toggleSearch.on('click', function(e) {
    e.stopPropagation();
    toggleSearch();
});

$(document.body).on('click', function(e) {
    if (isSearchFieldOpen) {
        var target = e.target;
        // Checking if user clicks outside .search-expand
        if (!$searchExpand.is(target) && !$searchExpand.has(target).length) {
            toggleSearch();
        }
    }
});
  

我在网站上进行了第二次搜索,其代码与之前相同   使用div .toggle-serach2和.expand-search2,我该如何制作你的代码   所以它不会重叠。只需将名称更改为$(&#39; toggle-search2&#39;)   没有削减它

在这种情况下,我建议您将代码转换为插件:

(function($, document) {

    var bodyHandlerAttached = false;
    var openedForms = [];
    var instances = {};

    var defaults = {
        activeClass: 'active'
    };


    function ToggleSearch(elem, options) {
        this.options = $.extend({}, defaults, options);
        this.$elem = $(elem);
        this.$btn = $(options.toggleBtn);

        this.isOpen = false;
        this.id = generateId();

        this.bindEvents();

        instances[this.id] = this;

        if (!bodyHandlerAttached) {
            handleOutsideClick();
            bodyHandlerAttached = true;
        }
    }

    ToggleSearch.prototype = {
        bindEvents: function() {
            this.$btn.on('click', $.proxy(toggleHandler, this));
        },

        open: function() {
            if (this.isOpen) { return; }

            var _this = this;

            this.$btn.addClass(this.options.activeClass);
            this.$elem.fadeIn(250, function() {
                _this.$elem.find('input').focus();
            });

            openedForms.push(this.id);
            this.isOpen = true;
        },

        close: function(instantly) {
            if (!this.isOpen) { return; } 

            this.$btn.removeClass(this.options.activeClass);

            if (instantly) {
                this.$elem.hide();
            } else {
                this.$elem.fadeOut(250);
            }

            openedForms.splice(openedForms.indexOf(this.id), 1);
            this.isOpen = false;
        },

        toggle: function() {
            if (this.isOpen) {
                this.close();
            } else {
                this.open();
            }
        }
    };

    var toggleHandler = function(ev) {
        ev.stopPropagation();
        this.toggle();
    };

    var handleOutsideClick = function(e) {
        $(document.body).on('click', function(e) {
            if (openedForms.length) {

                var target = e.target;
                var instance;

                for (var id in instances) {
                    instance = instances[id];

                    if (!instance.$elem.is(target) && !instance.$elem.has(target).length) {
                        instance.close(true);
                    }
                }
            }
        });
    };

    function generateId() {
        return Math.random().toString(36).substr(2, 8);
    }


    $.fn.toggleSearch = function(options) {
        return this.each(function() {
            if (!$.data(this, 'toggleSearch')) {
                $.data(this, 'toggleSearch', new ToggleSearch(this, options));
            }
        });
    };

})(window.jQuery, document);

然后像这样使用它:

$('.search-expand').toggleSearch({
    toggleBtn: '.toggle-search'
});

$('.search-expand2').toggleSearch({
    toggleBtn: '.toggle-search2'
});

JSFiddle example

答案 3 :(得分:0)

尝试添加body点击监听器

$('body').click(function(e){
    if ($(e.target).is('.toggle-search')) return;
    $('.toggle-search').removeClass('active');
    $('.search-expand').fadeOut(250);
});