$(document).ready(function(){
$("ul.topnav li.ddmhover").hover(function() { //When trigger is hovered...
//Following events are applied to the subnav itself (moving subnav up and down)
$(this).parent().find("ul.subnav").slideDown('fast').show(); //Drop down the subnav on hover
// Right here you are attaching to .ddmhover's parent ".topnav",
// not .ddmhover, so it is sliding up when you mouseOut of ".topnav"
// This should be in a function that is a second parameter to your first
// .hover() call instead of this...
$(this).parent().hover(function() {
}, function(){
$(this).parent().find("ul.subnav").slideUp('slow').stop(true,true); //When the mouse hovers out of the subnav, move it back up
});
//Following events are applied to the trigger (Hover events for the trigger)
}).hover(function() {
$(this).addClass("subhover"); //On hover over, add class "subhover"
}, function(){ //On Hover Out
$(this).removeClass("subhover"); //On hover out, remove class "subhover"
});
Обновлено
Я переписал это, чтобы быть более обобщенным. Таким образом, вам не нужно иметь отдельное имя класса для каждого раскрывающегося списка и subnav, которые вы создаете. Вместо этого вы просто используете «.ddmhover» и «.subnav» для них всех.
$(document).ready(function(){
$("li.ddmhover").mouseover(function() {
var that = this,
subnav = $(this).find("ul.subnav"),
img = $(this).find('img'),
subnavTimeout;
$(this).addClass("subhover");
subnav.slideDown('fast');
var hideSubnav = function (evt) {
// Wait half a second before trying to hide subnav
subnavTimeout = setTimeout( function () {
$(subnav).unbind('mouseleave');
$(subnav).slideUp('slow');
$(that).removeClass("subhover");
}, 500);
};
$(subnav).mouseleave(hideSubnav)
// since the title image fills the whole .ddmhover li we must attach to the image itself
$(img).mouseleave(hideSubnav);
// If the mouse entered the subnav don't close the subnav
$(subnav).mouseenter(function () {
clearTimeout(subnavTimeout);
});
});
});
Мы все время от времени делаем это, но всякий раз, когда вы обнаруживаете, что копируете / вставляете кусок кода, а затем меняете одну или две строки, было бы лучше вместо этого создать обобщенный метод работы с ним.