问题
I have created an DOM element for an MDC slider (https://material.io/develop/web/components/sliders).
It looks nice (except for the colors). And it works, but I really have no idea how to initialize it.
I import MDC from the CDN. I can't understand from the documentation how to do the initialization. This is one version that works:
setTimeout(() => { slider = new mdc.slider.MDCSlider(eltSlider) });
Without setTimeout
it does not work.
I have tried using a Promise instead and wait a second. That does not work.
And maybe even worse: If I use a Promise to wait after the setTimeout it does not work any more.
What is going on and how am I supposed to do it?
I do not use ts. And I do not use any package handler. Just plain JavaScript. (And I would be glad if the documentation covered this use case first.)
(There seems to be only one other question about MDCSlider here. It does not cover my question: actual use of foundation and adapter class of mdc-components)
EDIT: By "import from CDN" I mean the setup mentioned here: https://material.io/develop/web/docs/getting-started
<link href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css" rel="stylesheet">
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
There is no JavaScript error. It is just the slider on the screen that does not work. (It looks ok, but it does not work.)
I think this is a problem with MDC and the DOM state. The example in the link above suggests that the DOM is ready, but it does not say so. And it does not explain how to check this when manipulating the DOM with JavaScript.
回答1:
Here is some documentation about using MDC Web in plain JavaScript - https://material.io/develop/web/docs/importing-js, section "Global / CDN".
- Make sure you call JavaScript after slider HTML is loaded. Usually I insert it just before the closing
body
tag. - Here is an example of slider initialization code for JavaScript:
const MDCSlider = mdc.slider.MDCSlider;
const slider = new MDCSlider(document.querySelector('.mdc-slider'));
Here is a minimum working example of the MDCSlider - https://jsfiddle.net/klyakh/oky0zf7e/1/
来源:https://stackoverflow.com/questions/64892909/how-do-i-use-mdcslider-in-javascript