我有一个基本的html页面,带有导航栏(导航栏文档(和可折叠的侧导航(SideNav文档(。侧导航本身工作正常,但"onOpenStart"和"onEndClose"事件都在页面加载完成后立即触发,而不是在侧边导航打开/关闭时触发。
我想另一种方法是在侧导航触发器上挂接一些事件并从那里开始,但如果这些事件已经存在,这似乎没有必要。
小提琴:https://jsfiddle.net/gvgo2Lu2/2/
任何帮助将不胜感激
.HTML
<head>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
</head>
<body>
<nav>
<div class="nav-wrapper">
<div class="row">
<div class="col s12">
<a href="#!" class="brand-logo">Logo</a>
<a href="#" data-target="mobile-nav" class="sidenav-trigger">
<i id="test" class="material-icons">menu</i>
</a>
<ul class="right hide-on-med-and-down">
<li>
<a href="#!">Link</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<!-- MOBILE NAV -->
<ul class="sidenav" id="mobile-nav">
<li>
<a href="#!">Link</a>
</li>
</ul>
</body>
.JS
var elem = document.querySelector('.sidenav');
var instance = M.Sidenav.init(elem, {
onOpenStart: console.log("I trigger as soon as the page is loaded"),
onCloseEnd: console.log("same")
});
根据文档,onOpenStart 和 onCloseEnd 事件需要一个回调函数。但是,您正在使用计算结果:console.log(....(。由于该值未定义,因此不会添加事件处理程序!
为了克服这个问题,您需要将 init 更改为(更新的小提琴(:
var elem = document.querySelector('.sidenav');
var instance = M.Sidenav.init(elem, {
onOpenStart: function () {
console.log("I trigger as soon as the page is loaded");
},
onCloseEnd: function () {
console.log("same");
}
});
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/css/materialize.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0-beta/js/materialize.min.js"></script>
<nav>
<div class="nav-wrapper">
<div class="row">
<div class="col s12">
<a href="#!" class="brand-logo">Logo</a>
<a href="#!" data-target="mobile-nav" class="sidenav-trigger">
<i class="material-icons">menu</i>
</a>
<ul class="right hide-on-med-and-down">
<li>
<a href="#!">Link</a>
</li>
</ul>
</div>
</div>
</div>
</nav>
<!-- MOBILE NAV -->
<ul class="sidenav" id="mobile-nav">
<li>
<a href="#!">Link</a>
</li>
</ul>