您从未提到过使用 Javascript,但这里有一个使用它来关闭菜单并单击元素的版本(注意:从下面的 url 对 css 稍作更改):
var menu = document.querySelector('.menu-outer');
var links = document.querySelectorAll('nav ul li a');
var addClass = function(element, className) {
if (element.classList) {
element.classList.add(className);
} else {
removeClass(element, className);
element.className = (element.className + ' ' + className).replace(/^\s/, '');
}
};
var removeClass = function(element, className) {
if (className.indexOf('*') !== -1) {
var aryClasses = element.className.split(' ');
for (var i = 0; i < aryClasses.length; i++) {
if (aryClasses[i].indexOf(className.replace('*', '')) !== -1) {
element.removeClass(aryClasses[i]);
}
}
} else {
if (element.classList) {
element.classList.remove(className);
} else {
element.className = element.className.replace(new RegExp('(^|\\b)' + className.split(' ').join('|') + '(\\b|$)', 'gi'), ' ');
}
}
};
var open = function() {
console.log('opening');
addClass(menu, 'active');
};
var close = function() {
console.log('closing');
removeClass(menu, 'active');
};
if (menu) {
menu.addEventListener('mouseover', open, false);
menu.addEventListener('mouseout', close, false);
for (var l = 0; l < links.length; l++) {
var link = links[l];
link.addEventListener('click', close, false);
}
}
jQuery 会是这样的:
$('body').on('click', 'nav ul li a', function() {
$('.menu-outer').removeClass('active');
});
$('body').on('mouseover', '.menu-outer', function() {
$(this).addClass('active');
});
$('body').on('mouseout', '.menu-outer', function() {
$(this).removeClass('active');
});
http://cssdeck.com/labs/x0lpogde
我是一名优秀的程序员,十分优秀!