0

我有一个带有导航栏(导航栏文档)和可折叠侧导航(侧导航文档)的基本 html 页面。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")
});
4

1 回答 1

3

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

为了克服这个问题,您需要将您的 init 更改为(更新的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>

于 2018-04-10T14:59:03.457 回答