关键JS代码:
import styles from './range.css';
class uiRange extends HTMLElement {
constructor () {
super();
// Shadow DOM元素
let shadow = this.attachShadow({
mode: 'open'
});
// 目前仅Chrome和Chromium Edge支持adoptedStyleSheets
if (shadow.adoptedStyleSheets) {
shadow.adoptedStyleSheets = [styles];
} else {
// 其他浏览器,需要同时没有import styles from './range.css'这一行才能执行
fetch('./range.css').then(response => response.text()).then(data => {
let node = document.createElement('style');
node.innerHTML = data;
shadow.appendChild(node);
});
// @import 语法使用示意
// let node = document.createElement('style');
// node.innerHTML = `@import './range.css';`;
// shadow.appendChild(node);
}
}
...
}
if (!customElements.get('ui-range')) {
customElements.define('ui-range', uiRange);
}