MaterialiseCSS - 未正确触发的SideNav事件

时间:2018-04-10 14:43:19

标签: javascript html materialize sidenav

我有一个基本的html页面,其中包含一个导航栏(Navbar Documentation)和一个可折叠的sidenav(SideNav Documentation)。 sidenav本身工作正常,但是“onOpenStart”和“onEndClose”事件都会在页面加载完成时触发,而不是在sidenav打开/关闭时触发。 我想一个替代方法是将一些事件挂钩到sidenav-trigger并从那里开始,但如果这些事件已经存在,这似乎是非常必要的。

JsFiddle: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")
});

1 个答案:

答案 0 :(得分:1)

根据文档, onOpenStart onCloseEnd 事件需要回调函数。但是,您正在使用计算结果:console.log(....)。因为该值未定义,所以您不添加事件处理程序!

为了克服这个问题,您需要将init更改为(updated fiddle):

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>