使用 Chrome DevTools 将鼠标悬停在自定义元素上时,自定义元素未被标记

Custom Elements are not getting marked when hovering over them with Chrome DevTools

我有一个主要的 html 文件,我在其中嵌入了 Web 组件。 调试时我注意到,当我将鼠标悬停在自定义元素上时,我的自定义元素未被标记。

我也无法从外部设置自定义 html 元素的大小 css。

这是我的代码:

view.html

    <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <link href="view.css" rel="stylesheet" />
    <script defer src="widget-uhr.js"></script>
</head>

<body>
    <widget-uhr></widget-uhr>
    <widget-uhr></widget-uhr>
    <widget-uhr></widget-uhr>
    <button>View Button</button>
</body>
</html>

小部件-uhr.html

   <!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <link href="widget-uhr.css" rel="stylesheet" />
</head>

<body>
    <div id="time"></div>
    <button>Widget Button1</button>
    <button>Widget Button2</button>
    <button>Widget Button3</button>
</body>
</html>

view.css

body{
    display:block;
}
button{
    min-width: 250px;
    min-height: 100px;
    background-color: aqua;
    font-size: 32px;
}

小部件-uhr.css

body{
color:green;
background-color: gray;
}

div{
    color:blue;
    background-color: gray;
}

button{
    background-color: red;
}

小部件-uhr.js

fetch( "widget-uhr.html" )
    .then( stream => stream.text() )
    .then( text => 
        customElements.define( "widget-uhr", class extends HTMLElement {
            constructor() {
                super()
                this.attachShadow( { mode: 'open'} )
                    .innerHTML = text


            }
        } )
    )

原因可能是因为我通过提取从小部件中注入了 html?

外在风格

Im also not able to set the size of the custom html element from an outisde css.

使用阴影 DOM CSS 选择器不会跨越阴影边界。我们对外界进行了样式封装。

您可以将规则包含在影子树的样式元素中。

 <style>
   @import url( 'view.css' )
 </style>

More information here

Chrome 检查员

When debugging I noticed, that my Custom Elements are not marked, when I hover over them. You have to enable Shadow DOM inspector first.

  1. 使用 F12 打开您的开发工具
  2. 点击右上角的三个点
  3. 点击设置
  4. 在元素类别下启用选项“显示用户代理阴影 DOM”

默认情况下自定义元素是内联,因此它不会在开发工具中被标记。

要标记它,您应该将其 CSS display 属性 定义为 blockinline-block.

从其影子 DOM 内部,使用 :host CSS 伪 class。

小部件中-uhr.css:

:host { display: block }

或者,在主文档中,使用自定义元素名称。

view.css:

widget-uhr { display: block }