我创建了一个 custom element使用 Javascript 并且在我的自定义元素中是一个范围类型的输入。现在我想设计它的样式,但它不起作用。
我尝试使用 Javascript 以及链接到我的 HTML 页面的外部 CSS 文件来设置元素的样式。
我用了::-webkit-slider-thumb
为拇指设置样式,因为我希望它是一个圆圈。
(function(){
const template = document.createElement("template");
template.innerHTML = `
<style>
</style>
<input type="range" min="-100" max="100" value="0">
`;
class SliderElement extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({mode: 'open'});
this.shadowRoot.appendChild(template.content.cloneNode(true));
}
connectedCallback() {
}
}
customElements.define('slider-element', SliderElement);
})();
<!doctype html>
<html lang="de">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="css/style.css">
<script src="js/slider.js" defer></script>
</head>
<body>
<slider-element></slider-element>
</body>
</html>
当我尝试设置 <slider-element>
的样式时与 ::-webkit-slider-thumb
我希望它能起作用。如果我可以在 style.css
中设置自定义元素的样式就好了.
最佳答案
当使用影子 DOM 时,样式会在“影子边界”处停止。阴影根之外的样式不会应用于它内部的元素。 As per html5rocks (他以 h3
元素为例,强调他的):
There are other h3s on this page, but the only one that matches the h3 selector, and therefore styled red, is the one in the ShadowRoot. Again, scoped styles by default.
Other styles rules defined on this page that target h3s don't bleed into my content. That's because selectors don't cross the shadow boundary.
因此,您必须在包含在 template.innerHTML
中的样式标签内为您的自定义元素定义样式。例如(我从 here 获得了 slider 的样式):
template.innerHTML = `
<style>
input[type=range]{
-webkit-appearance: none;
}
input[type=range]::-webkit-slider-runnable-track {
width: 300px;
height: 5px;
background: #ddd;
border: none;
border-radius: 3px;
}
input[type=range]::-webkit-slider-thumb {
-webkit-appearance: none;
border: none;
height: 16px;
width: 16px;
border-radius: 50%;
background: goldenrod;
margin-top: -4px;
}
</style>
<input type="range" min="-100" max="100" value="0">
`;
JSFiddle here
关于javascript - 如何在 shadowtree 中设置 <input type ="range"> 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57256270/