MaterializeCSS模式未打开

时间:2018-12-01 18:17:17

标签: javascript materialize

这是我的Modal HTML代码:

<div class="modal">
  <div class="modal-content">
    <h4>Modal Header</h4>
    <p>A bunch of text</p>
  </div>
  <div class="modal-footer">
    <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a>
  </div>
</div>

这就是我在JS中引用它的方式:

function aFunction() {
    var elem = document.querySelector('.modal');
    var instance = M.Modal.getInstance(elem);
    instance.open();
}

我在单击按钮时调用该函数,但是模态不显示。我注意到的唯一变化是右侧的滚动条消失了。

1 个答案:

答案 0 :(得分:0)

您使用的是哪个版本?

在示例the docs中针对v1.0.0的方式是这样的:

document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('.modal');
  var instances = M.Modal.init(elems);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
<!-- Modal Trigger -->
<button data-target="modal1" class="btn modal-trigger">Open the modal</button>

<button class="btn">Do something else</button>

<!-- Modal Structure -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <h4>Modal Header</h4>
    <p>A bunch of text</p>
  </div>
  <div class="modal-footer">
    <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a>
  </div>
</div>

或者,如果您想以编程方式(通过自己的函数)打开它,则需要先启动模式。

document.addEventListener('DOMContentLoaded', function() {

  var elems = document.querySelectorAll('.modal');
  var instances = M.Modal.init(elems);
  
  var singleModalElem = document.querySelector('#modal1');
  var instance = M.Modal.getInstance(singleModalElem);
  const modalbtn = document.querySelector('#open')
  modalbtn.addEventListener('click', () => {
    instance.open();
    // Do other stuff
  })
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<!-- Modal Structure -->
<div id="modal1" class="modal">
  <div class="modal-content">
    <h4>Modal Header</h4>
    <p>A bunch of text</p>
  </div>
  <div class="modal-footer">
    <a href="#!" class="modal-close waves-effect waves-green btn-flat">Agree</a>
  </div>
</div>

<button id="open">Open a single modal</button>