我在onShow上使用Superfish调用了这个工作函数,它工作正常,但我认为它看起来有点臃肿,我可以阅读它。我是一名艺术家,所以这些东西(现在几年)仍然是一个大脑体操。
如果有人有一个例子,不需要重写,只是一个类似的例子来缩短或提示,这就是我想要的。
/** ==============================================================================
* superfish edge detection
=============================================================================== */
function superfish_edge_detection() {
var window_width = $(window).width();
$('.nav-primary ul ul li').mouseover(function() { // yes, you must repeat this again
if ( $( '#collapse-break-point' ).is( ':hidden' ) ) {
var sub_menu_exist = $( this ).find( '.sub-menu' ).length;
if ( sub_menu_exist > 0 ) {
var sub_menu_width = $( this ).find('.sub-menu').width();
var sub_menu_offset = $( this ).find('.sub-menu').parent().offset().left + sub_menu_width;
// if sub menu is off screen
if ((sub_menu_offset + sub_menu_width) >= window_width) {
var new_sub_menu_position = sub_menu_width + 0;
$(this).find('.sub-menu').css({
left: -new_sub_menu_position,
top: '0',
});
} // end is off screen
else if ( (sub_menu_offset + sub_menu_width ) <= window_width )
{
$(this).find('.sub-menu').css({
left: '100%'
});
} //end not off screen
}
} //if breakpoint is hidden
else
{
$( '.sub-menu' ).removeAttr( 'style' );
} //breakpoint is not hidden
}); //end mouseover function
} //end superfish_edge_detection();
在桑蒂的帮助下(见答案,这是修订版):
答案 0 :(得分:3)
将子菜单存储为一个变量,不仅可以缩短脚本,还可以提高速度。通过一遍又一遍地使用.find()
,JQuery必须在每次调用时继续寻找元素。
function superfish_edge_detection() {
var window_width = $(window).width();
$('.nav-primary ul ul li').mouseover(function() { // yes, you must repeat this again
var $sub_menu = $(this).find('.sub-menu');
if ( $( '#collapse-break-point' ).is( ':hidden' ) ) {
var sub_menu_exist = $sub_menu.length;
if ( sub_menu_exist > 0 ) {
var sub_menu_width = $sub_menu.width();
var sub_menu_offset = $sub_menu.parent().offset().left + sub_menu_width;
// if sub menu is off screen
if ((sub_menu_offset + sub_menu_width) >= window_width) {
var new_sub_menu_position = sub_menu_width + 0;
$sub_menu.css({
left: -new_sub_menu_position,
top: '0',
});
} // end is off screen
else if ( (sub_menu_offset + sub_menu_width ) <= window_width )
{
$sub_menu.css({
left: '100%'
});
} //end not off screen
}
} //if breakpoint is hidden
else
{
$sub_menu.removeAttr( 'style' );
} //breakpoint is not hidden
}); //end mouseover function
} //end superfish_edge_detection();