JavaScript Onclick下拉菜单不起作用
我想为网站做一个onclick下拉菜单。当我单击.dropdown元素时,我希望我的.sublink元素向下滑动,然后当我点击页面上的任何其他位置时,.sublink将滑回备份。JavaScript Onclick下拉菜单不起作用
菜单下降,但当我点击网站上的其他位置时,它不会滑回。
以下是我目前菜单中的代码。有人可以帮助我吗?谢谢!
$(function() {
$('.dropdown').click(function() {
$('.sublinks').stop(false, true).hide();
var submenu = $(this).parent().next();
submenu.css({
position: 'absolute',
top: $(this).offset().top + $(this).height() + 'px',
left: $(this).offset().left + 'px',
zIndex: 1000
});
submenu.stop().slideDown(300);
//click anywhere outside the menu
$(document).click(function() {
var $el = $(this);
$el.not('.dropdown') && $el.slideUp(300);
});
});
});
在你的代码,这是点击文件的任何地方,这将指向一个文件,还没到发生事件的实际元素。您可以修改您的代码像下面(使用e.target代替this
):
$(function() {
$('.dropdown').click(function() {
$('.sublinks').stop(false, true).hide();
var submenu = $(this).parent().next();
submenu.css({
position: 'absolute',
top: $(this).offset().top + $(this).height() + 'px',
left: $(this).offset().left + 'px',
zIndex: 1000
});
submenu.stop().slideDown(300);
});
//click anywhere outside the menu
$(document).click(function(e) {
var $el = $(e.target);
if(!$el.hasClass('.dropdown') && $el.closest(".dropdown").length == 0 && !$el.hasClass('.sublinks') && $el.closest(".sublinks").length == 0)
$('.sublinks:visible').slideUp(300);
});
});
参见$el.closest(".dropdown").length == 0
它是确保点击发生不是在.dropdown
子元素这里是它的一个演示。点击不同的位置并检查控制台:http://jsfiddle.net/2ryWF/。你会发现这总是指向文档
看起来你的钩点击任何地方的下拉菜单点击钩内, 尝试这样的事情(未测试);
$(function() {
//click on menu(dropdown div)
$('.dropdown').click(function() {
$('.sublinks').stop(false, true).hide();
var submenu = $(this).parent().next();
submenu.css({
position: 'absolute',
top: $(this).offset().top + $(this).height() + 'px',
left: $(this).offset().left + 'px',
zIndex: 1000
});
submenu.stop().slideDown(300);
});
//click anywhere in document
$(document).click(function() {
var $el = $(this);
$el.not('.dropdown') && $el.slideUp(300);
});
});
尝试使用blur event:
$('.dropdown').blur(function() {
var $submenu = (...); // <- get submenu selector here
$submenu.slideUp();
});
我只能说它只能用于表单元素(在这种情况下,.dropdown很可能是div,ul或类似的东西,而不是表单元素),但正如我所看到的(http://www.quirksmode.org/dom/events/blurfocus.html),如果任何元素具有tabindex属性集合,则可能会发生焦点和模糊事件 – 2013-02-12 17:30:26
这是迄今为止最接近的解决方案...但菜单仍然没有滑动。无论我点击什么,都可以通过此代码滑出屏幕。帮帮我! – 2013-02-12 18:23:20
查看更新的代码。我认为不会正常工作,但那不是你需要的。另外,将'$(document).click(function(e){''''('。dropdown')'外部)点击(function(){',否则点击处理程序将在每次打开时添加到文档中 – 2013-02-12 18:28:47
以下是我在jsfiddle上的页面:http://jsfiddle.net/2ryWF/2/请注意,您点击的任何东西都会滑落并消失;同样,下拉菜单不会消失,直到您单击每个链接,但是,当我点击页面的其他任何地方时,我只想要整个下拉菜单向上滑动。 – 2013-02-12 18:43:55