1
我試圖用下拉菜單創建一個簡單的導航菜單。我使用jQuery將'data-dropdown'屬性設置爲'opened'或'closed',以用於後期CSS。我使用'Modernizr.touchevents'來決定懸停/點擊行爲。這裏是我的代碼:jQuery下拉菜單點擊可點擊(第二次點擊)父母
(function ($) {
"use strict";
var menu = $('.navbar .menu');
// Return early if there's no menu
if (! menu) {
return;
}
var dropdownLi = menu.find('.menu-item-has-children');
var dropdownLink = menu.find('.menu-item-has-children > a');
// Return early if there's no dropdown
if (! dropdownLi) {
return;
}
// Set attr to all dropdowns by default
dropdownLi.attr('data-dropdown', 'closed');
// Use modernizr to decide on touch/hover behaviour
if (Modernizr.touchevents) {
dropdownLink.click(function(event) {
// Set 'data-dropdown' attr to 'opened'
$(this).parent().attr('data-dropdown', 'opened');
// Set 'data-dropdown' attr on other submeus to 'closed'
$(this).parent().siblings().attr('data-dropdown', 'closed');
// Set 'data-dropdown' attr on other nested subenus to 'closed'
$(this).parent().siblings().find('.menu-item-has-children').attr('data-dropdown', 'closed');
// Prevent default click
return false;
// event.preventDefault();
// event.stopImmediatePropagation();
});
// Close all menus on scroll
$('.site-wrapper').scroll(function() {
dropdownLi.attr('data-dropdown', 'closed');
});
// Close all dropdowns when clicked anywhere
$(document).click(function() {
dropdownLi.attr('data-dropdown', 'closed');
});
} else { // Now hover behaviour
dropdownLi.each(function() {
$(this).mouseenter(function() {
$(this).attr('data-dropdown', 'opened');
});
$(this).mouseleave(function() {
$(this).attr('data-dropdown', 'closed');
});
});
// Prevent default click if there's just a `#` instead of a link
dropdownLink.on('click', function(){
if (this.href.indexOf('#') != -1) {
return false;
// event.preventDefault();
// event.stopImmediatePropagation();
}
});
}
})(jQuery);
而現在的問題。 'dropdownLink'可以有一個有效的href屬性(不是#)。在這種情況下,我需要在第二次點擊時採取行動。因此,在觸控設備上,第一次點擊會打開下拉菜單,第二次則會將我們發送到網址。
正確的答案是!現在我正在質疑自己,我是如何不明白這一點的。謝謝! – Baltar
有時你只是盯着它太久,然後迷失在你自己的想法!很高興我能幫上忙 :) –