使 mmenu 扩展到当前 url
Make mmenu expand to the current url
我正在使用 mmenu 来创建一个漂亮的响应式菜单。效果很好,但我希望它能打开与当前 url 匹配的列表项。这样,如果您进入网站并打开菜单,您可以立即看到您所在的位置。我一直在尝试使用 api 来实现此功能。
mmenu 的 api 文档参见上文 link。
我的代码:
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
var api = $("nav#menu").data("mmenu");
api.bind("openPanel", function($panel) {
console.log("This panel is now opened:" + $panel.attr("id")); //Works
var href = $panel.find("li a").attr("href");
if (href == url) {
api.openPanel($panel); //Open the panel where the matching link is - doesn't work
console.log("Success!" + href);
}
});
我只是无法让它工作。有什么想法吗?
我处理你的 JS Fiddle 与你最初设置的有点不同,所以我希望它仍然对你有用。
Mmenu 有一个名为 "classNames" 的配置对象,您可以在 li
上传递 class,您希望默认使用 "selected" 对象。这是使用此设置更新的 mmenu init:
$("#menu").mmenu({
"offCanvas": {
"zposition": "front"
}
}, {
classNames: {
selected: "current-page"
}
});
我在调用此 init 之前所做的是循环遍历菜单中的 <a>
标记,以将 href 与 url 变量相匹配,然后将 class 添加到parent <li>
找到匹配时(注意:这使用您现有的 url var 逻辑)。
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$('#menu a').each(function(){
var href = $(this).attr("href");
if ( href == url ){
$(this).parent('li').addClass('current-page');
}
});
在 JS Fiddle 上,href 的 none 匹配 window.location
,所以我只是将 class 硬编码到第三层抽屉之一上你可以看到它在工作。当你在你的设置上尝试这个时,你显然想要删除硬编码的 class.
我正在使用 mmenu 来创建一个漂亮的响应式菜单。效果很好,但我希望它能打开与当前 url 匹配的列表项。这样,如果您进入网站并打开菜单,您可以立即看到您所在的位置。我一直在尝试使用 api 来实现此功能。
mmenu 的 api 文档参见上文 link。
我的代码:
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
var api = $("nav#menu").data("mmenu");
api.bind("openPanel", function($panel) {
console.log("This panel is now opened:" + $panel.attr("id")); //Works
var href = $panel.find("li a").attr("href");
if (href == url) {
api.openPanel($panel); //Open the panel where the matching link is - doesn't work
console.log("Success!" + href);
}
});
我只是无法让它工作。有什么想法吗?
我处理你的 JS Fiddle 与你最初设置的有点不同,所以我希望它仍然对你有用。
Mmenu 有一个名为 "classNames" 的配置对象,您可以在 li
上传递 class,您希望默认使用 "selected" 对象。这是使用此设置更新的 mmenu init:
$("#menu").mmenu({
"offCanvas": {
"zposition": "front"
}
}, {
classNames: {
selected: "current-page"
}
});
我在调用此 init 之前所做的是循环遍历菜单中的 <a>
标记,以将 href 与 url 变量相匹配,然后将 class 添加到parent <li>
找到匹配时(注意:这使用您现有的 url var 逻辑)。
var url = window.location.href.substr(window.location.href.lastIndexOf("/") + 1);
$('#menu a').each(function(){
var href = $(this).attr("href");
if ( href == url ){
$(this).parent('li').addClass('current-page');
}
});
在 JS Fiddle 上,href 的 none 匹配 window.location
,所以我只是将 class 硬编码到第三层抽屉之一上你可以看到它在工作。当你在你的设置上尝试这个时,你显然想要删除硬编码的 class.