我试图在一页上使用2个jQuery
导航脚本(台式机为Superfish
,移动版为FlexNav
)。我目前正在使用Paul Paul Irish的matchMedia
和polyfill
来响应CSS3
中JavaScript
媒体查询状态的更改。
当前的代码仅完成了总体目标的50%。如果最初以等于或大于999px的窗口大小访问网页,则得到Superfish
;如果最初以小于999px的窗口访问网页,则得到FlexNav
。当两个脚本都变为 Activity 状态时,在999px上方或下方调整窗口大小时,会发生此问题。
// media query event handler
if (matchMedia) {
var mq = window.matchMedia("(min-width: 999px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
$("ul.sf-menu").superfish({
delay: 350,
speed: 400,
});
} else {
$("ul.flexnav").flexNav({
'animationSpeed': '250',
'transitionOpacity': true,
'buttonSelector': '.menu-button',
'hoverIntent': false
});
}
}
我想使用
matchMedia
进行此工作,我愿意接受所有建议。更新:由于Stephan的建议,我现在有以下代码:
jQuery(document).ready(function () {
// add destroy function for FlexNav
flexNavDestroy = function () {
$('.touch-button').off('touchstart click').remove();
$('.item-with-ul *').off('focus');
}
// media query event handler
if (matchMedia) {
var mq = window.matchMedia("(min-width: 999px)");
mq.addListener(WidthChange);
WidthChange(mq);
}
// media query change
function WidthChange(mq) {
if (mq.matches) {
if (typeof (flexNav) != "undefined") {
flexNavDestroy();
}
superfish = $("ul.sf-menu").superfish({
delay: 350,
speed: 400,
});
} else {
if (typeof (superfish) != "undefined") {
superfish.superfish('destroy');
}
flexNav = $("ul.flexnav").flexNav({
'animationSpeed': '250',
'transitionOpacity': true,
'buttonSelector': '.menu-button',
'hoverIntent': false
});
}
}
});
剩余问题:
FlexNav
的destroy函数只是部分销毁它。 最佳答案
最好的方法可能是在激活一个插件时销毁另一个插件。
如果我在Superfish的源代码中查找,则有一个destroy函数可以做到这一点,但是flexNav没有这样的函数。您可以创建一个:
flexNavDestroy = function(){
$('.touch-button').off('touchstart click').remove();
$(('.item-with-ul *').off('focus');
}
然后,您可以这样做:
function WidthChange(mq) {
if (mq.matches) {
if(typeof(flexNav) != "undefined") {
flexNavDestroy();
}
superfish = $("ul.sf-menu").superfish({
delay: 350,
speed: 400,
});
} else {
if(typeof(superfish) != "undefined") {
superfish.superfish('destroy');
}
flexNav = $("ul.flexnav").flexNav({
'animationSpeed': '250',
'transitionOpacity': true,
'buttonSelector': '.menu-button',
'hoverIntent': false
});
}
}
更新
我已经对FlexNav进行了更多研究,但我错过了一些东西。
我认为样式之间存在冲突,因为FlexNav默认情况下会设置很多样式。我们可以使用两种方法轻松地避免这种情况:一种用于flexnav样式(默认
.flexnav
),可以将其删除以隐藏所有样式;另一种用于绑定(bind)javascript函数(该函数始终存在,否则我们无法重新定位)附上)。我通常喜欢在
js-
之前加上任何表示JS钩子(Hook)的类,因此在下面的示例中,我将菜单上的.flexnav
类替换为.js-flexnav
。然后要激活flexnav,您必须在调用$('ul.flexnav').flexNav()
之前添加此行$('.js-flexnav').addClass('flexnav');
在destroy函数中,您将不得不再次删除该类,我将在稍后展示。
另外,我不确定Superfish是如何显示和隐藏的,但是由于FlexNav折叠了所有子菜单,因此可以肯定地说,您应该重新显示它们,以便Superfish能够自己做。
更新的destroy函数反射(reflect)了这一点:
function flexNavDestroy(){
$('.touch-button').off('touchstart click').remove();
$('.item-with-ul *').off('focus');
$('.js-flexnav').removeClass('flexnav').find('ul').show(); // removes .flexnav for styling, then shows all children ul's
}
这是一个jsFiddle,其中显示了使用新代码激活/停用flexNav的信息:http://jsfiddle.net/9HndJ/
让我知道这是否对您有用!