我想使用 JS 添加 MDL 库的新 slider 组件。 当我在 HTML 中定义 slider 组件时,该组件已正确加载,但当我尝试使用 javascript 添加它时,样式未应用于 slider 。 为什么会发生这种情况? 图书馆链接:https://getmdl.io/components/index.html#sliders-section 我在主页上看到有一种特殊的方式可以动态显示组件,但我不明白它是如何工作的。 链接:https://getmdl.io/started/index.html
function create()
{
var element = document.createElement("input");
element.className = "mdl-slider mdl-js-slider";
element.setAttribute("type","range");
element.setAttribute("min","0");
element.setAttribute("value","0");
element.setAttribute("max","100");
element.setAttribute("tabindex","0");
document.getElementById("c").appendChild(element);
}
<head>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</head>
<body>
<div id="c">
<input class="mdl-slider mdl-js-slider" type="range" min="0" max="100" value="0" tabindex="0">
<button onclick="create()">Click me</button>
</div>
</body>
最佳答案
当使用 MDL 动态创建元素时,您需要使用 upgradeElement
函数注册新元素。在您的特定情况下,您的代码将如下所示:
function create()
{
var element = document.createElement("input");
element.className = "mdl-slider mdl-js-slider";
element.setAttribute("type","range");
element.setAttribute("min","0");
element.setAttribute("value","0");
element.setAttribute("max","100");
element.setAttribute("tabindex","0");
document.getElementById("c").appendChild(element);
componentHandler.upgradeElement(element); // <--- Note the MDL element registration
}
<强> Working Codepen
Material Design Lite Documentation 的适用部分:
Material Design Lite will automatically register and render all elements marked with MDL classes upon page load. However in the case where you are creating DOM elements dynamically you need to register new elements using the
upgradeElement
function.
关于javascript - Material Design Lite 和 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462771/