How I can open a materialize modal when a window i

2019-04-13 14:53发布

I want to open a modal window when the user be in a window, I mean, open a modal without a trigger button, I have this example.

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

It works if I click on the trigger button, but I don't want a click. I use this code when the window is ready:

$(function()
{
    function checkCode()
    {
        $("#btn-1").click();
    }
});

This automatically push the button and make the effect that modal is auto opened, but I don't want to do this.

7条回答
Emotional °昔
2楼-- · 2019-04-13 15:29

you can do that :

    $(document).ready(function(){
       $('.modal1').modal('open');
    });
查看更多
一纸荒年 Trace。
3楼-- · 2019-04-13 15:34

In case you are still having problems given the other solutions, I had to nest the jQuery('#modal_id').modal('open') statement in a second document.ready statement like so:

jQuery(document).ready(function(){
      jQuery('#modal_id').modal();
      jQuery(document).ready(function(){
          jQuery('#modal_id').modal('open');
      });
});

I don't know why this works, and I know it's just plain ugly, but it works so..

查看更多
ら.Afraid
4楼-- · 2019-04-13 15:36

You need to determine which event makes sense to trigger the modal to be displayed. onload or onmouseover may work for you instead of onclick.

查看更多
做个烂人
5楼-- · 2019-04-13 15:41

This can be done with instance.open().

<script>
        document.addEventListener('DOMContentLoaded', function () {
            var Modalelem = document.querySelector('.modal');
            var instance = M.Modal.init(Modalelem);
            instance.open();
        });

</script>
查看更多
劫难
6楼-- · 2019-04-13 15:43

I found the solution in materialize.js We must use:

$(".MyModal").openModal()

to open modals and:

$(".MyModal").closeModal()

to close it. Materialize team forgot refresh their documentation.

查看更多
男人必须洒脱
7楼-- · 2019-04-13 15:46

Pure JavaScript solution.

const elem = document.getElementById('modal id here');
const instance = M.Modal.init(elem, {dismissible: false});
instance.open();
查看更多
登录 后发表回答