首页 > 解决方案 > Initialize Slider in materialize css

问题描述

I copied the example code for the materialize slider and pasted it into my html. I linked the html with a JavaScript file, where I placed an

M.AutoInit();

Which should initialize all JS components of materialize.css (Carousel works in my html)

This is the related html:

<div class="row ">
    <div class="col s12 m12 ">
        <div class="slider">
            <ul class="slides">
                <li>
                    <img src="https://lorempixel.com/580/250/nature/4">
                    <!-- random image -->
                    <div class="caption center-align">
                        <h3>This is our big Tagline!</h3>
                        <h5 class="light grey-text text-lighten-3">Here's our small slogan.</h5>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</div>

And this is how I linked to the JavaScript: First materialize.js that app.js where I M.AutoInit();

<script type="text/JavaScript" src="../js/materialize.js"></script>
<!-- <script type="text/JavaScript" src="../js/materialize.min.js"></script> -->
<script src="../app.js "></script>
</html>

I am confused, because the carousel works within the same setting but not the slider…</p>

标签: javascripthtmlcssmaterialize

解决方案


2 things to change in your code:

  1. Make sure your initialization code is executed just after the DOM Content is totally loaded
  2. Use the specific initializator of the slider instead of the generic one
  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.slider');
    var instances = M.Slider.init(elems);
  });

Working example with your code: https://codepen.io/jhervas/pen/mddNrZX


推荐阅读