javascript - 如何在 shadowtree 中设置 <input type ="range"> 样式?

标签 javascript html css

我创建了一个 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 中设置 &lt;input type ="range"> 样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57256270/

相关文章:

javascript - Angular 工厂模块获取 promise 数据

javascript - 如何在 extJS 标记字段中设置插入符位置

javascript - 带有字符串值的 html anchor 标记重定向

html - CSS 在 jQuery 拖放后没有正确更新,但在 Inspector 中可以

html - Flexbox 悬停使子菜单 txt 仅出现在悬停列中

javascript - 无法在 &lt;script&gt; 标签上对生成的 RSS 进行样式化

html - 无法在旋转木马上垂直对齐图像

javascript - 随机化一个 Angular ?

html - html中的公共(public)元素

javascript - 我可以使用 HOC 用 graphql 和 redux 包装组件吗