All,
I am new to JQuery and trying to write JQuery code to create a multi level dropdown menu. The HTML looks like below:
<ul id="menu">
<li><a href="#">Link 1</a>
<ul class="submenu">
<li><a href="#">Sub Link 1.1</a>
<ul class="submenu">
<li><a href="#"> Sub Link 1.1.1</a></li>
<li><a href="#"> Sub Link 1.1.2</a></li>
</ul>
</li>
<li><开发者_JAVA技巧;a href="#">Sub Link 1.2</a></li>
<li><a href="#">Sub Link 1.3</a></li>
</ul>
</li>
<li><a href="#">Link 2</a>
<ul class="submenu">
<li><a href="#">Sub Link 2.1</a>
<ul class="submenu">
<li><a href="#"> Sub Link 2.1.1</a></li>
<li><a href="#"> Sub Link 2.1.2</a></li>
</ul>
</li>
<li><a href="#">Sub Link 2.2</a></li>
</ul>
</li>
</ul>
The JQuery code I got so far is as under, but it's not opening and closing the submenus.How can I make it work?
$(document).ready(function () {
$('#ul.menu > li').hover(function () { $('ul:first', this).show(); },
function () { $('ul:first', this).hide(); }
);
$('#ul.menu li li').hover(function () {
$('ul:first', this).each(function () {
var p = $(this).parent();
$(this).css('top', p.position().top)
.css('left', p.position().left + p.width())
.show();
});},
function () { $('ul:first', this).hide(); }
);
});
Chick this out: http://jsfiddle.net/g5xSX/ , maybe it is exactly what you want
I created this fiddle, it's just a start but some of it it's working http://jsfiddle.net/mZzqu/2/
I simplified your markup (attach click handler to 'li', it's better)
<ul id="menu">
<li>Link 1
<ul class="submenu">
<li>Sub Link 1.1
<ul class="submenu">
<li id='1'> Sub Link 1.1.1</li>
<li>Sub Link 1.1.2</li>
</ul>
</li>
<li>Sub Link 1.2</li>
<li>Sub Link 1.3</li>
</ul>
</li>
<li>Link 2
<ul class="submenu">
<li>Sub Link 2.1
<ul class="submenu">
<li> Sub Link 2.1.1</li>
<li> Sub Link 2.1.2</li>
</ul>
</li>
<li>Sub Link 2.2</li>
</ul>
</li>
</ul>
jquery code
$.fn.dropdown = function (options) {
var settings = jQuery.extend({
timeout: 0.2
}, options);
var closetimer = null;
var ddmenuitem = null;
$(this).children('li').each(function(){
$(this).find('ul').hide();
});
$(this).find('li').hover(dropdown_open, dropdown_close);
document.onclick = dropdown_close;
function dropdown_open(event)
{
dropdown_canceltimer();
//dropdown_close();
ddmenuitem = $(event.target).children('ul').css('display', 'block');
}
function dropdown_close(event) {
$(event.target).parent('ul:not(#menu)').hide();
}
function dropdown_timer() {
closetimer = window.setTimeout(dropdown_close, settings.timeout * 1000);
}
function dropdown_canceltimer() {
if (closetimer) {
window.clearTimeout(closetimer);
closetimer = null;
}
}
return this;
}
精彩评论