我正在尝试以插件的方式创建下拉菜单。我很熟悉编写解决方案的脚本,但我以前从未创建过插件,因此我试图学习如何做到这一点,从而提高我作为jQuery开发人员的水平。
我正在尝试创建基本的下拉功能。你有联系。点击它,就会出现一个下拉链接。单击链接(文档)外部,链接的菜单就会消失。
我在“走开”那部分遇到了麻烦。我试图将它绑定到document.click,但是当然,这会显示菜单,然后隐藏它,因为没有什么可以确保必须首先显示它。我该怎么做?
我如何使它,使菜单只隐藏后,它是显示,如果你点击它的外部?
application.js
jQuery(document).ready(function($){
$("ul.drop-down").sillyDropDown();
// failed attempt (shows and hides). Probably should go in plugin anyway.
// $(document).click(function(){
// $("ul.drop-down").sillyDropDown('hide');
// });
});silly_drop_down.js
(function($){
var methods = {
init : function(options){
return this.each(function(){
var $this = $(this);
var selector = $(this).children()[0];
var link = $(selector);
link.bind('click.silly', methods.show);
});
},
show : function() {
var $this = $(this);
var menu = $this.siblings("ul");
menu.slideDown("slow");
},
hide : function(){
var $this = $(this);
var menu = $this.children("ul");
menu.slideUp("slow");
}
};
$.fn.sillyDropDown = function(method){
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.sillyDropDown' );
}
};
})(jQuery);如果重要的话,可以使用html。
<ul id="project-settings" class="drop-down">
<li>
<a href="#">
Settings
<img src="/images/iconic/white/cog_alt_16x16.png" class="stale">
<img src="/images/iconic/orange/cog_alt_16x16.png" class="hover">
</a>
</li>
<ul style="display: none;">
<div class="pointer"></div>
<li class="first">
<a href="#">Settings...</a>
</li>
<li>
<a href="#">Collaborators...</a>
</li>
<li>
<a href="#">Comments...</a>
</li>
<hr>
<li>
<a href="#">Delete Project</a>
</li>
</ul>
</ul>编辑(我意识到我以前也问过类似的问题)。我在application.js中做了下面的工作
$("ul.drop-down").sillyDropDown();
$(document).bind("click.silly", function(e){
var nav = $("ul.drop-down");
var target = $(e.target);
if (target.closest("ul.drop-down").length < 1){
nav.sillyDropDown('hide');
return;
}
});这就是我的工作。然而,在application.js中这样做似乎不太优雅--我将如何在插件中处理这个问题?
注意:我可能会有多个ul.down的实例--在我的实现中是否遗漏了一些东西来解决这个问题?到目前为止,我的测试中只有一个.
另外,如果我单击下拉列表中的链接,我将如何使菜单隐藏(例如,这将是一个模式弹出)。
现在在application.js中添加了这个
$("ul.drop-down ul li a").click(function(e){
$("ul.drop-down ul").hide();
return;
});再次感觉,非常不雅致,可能应该放在其他地方。请教育我!
发布于 2011-02-11 10:42:12
我会将菜单关闭操作绑定到$(window).click,然后在下拉列表的单击事件中添加e.stopPropogation()。这样可以防止单击在DOM树上进一步冒泡到window元素。
或者只需使用菜单的blur事件。即使是在非输入元素上也会有效果。
发布于 2011-02-11 10:57:47
下面是一个例子:http://jsfiddle.net/5tgGq/1/。重要的部分是在init
init: function(options) {
return this.each(function() {
var self = this;
$(this).click(methods.show);
$(document).click(function(e) {
if ($(self).has(e.target).length === 0) {
methods.hide.apply(self);
}
});
});
},希望这能有所帮助。我非常肯定,您也可以使用多个元素,因为您只对已经编辑的元素使用show和hide方法。
编辑:下面是两个列表的示例:http://jsfiddle.net/5tgGq/3/
https://stackoverflow.com/questions/4967300
复制相似问题