[英]shadow dom not attaching on class that inherit from HTMLButtonElement
I am trying to attach shadow dom to this but it does not attach and gives a error DOMExpection operation is not supported but when inherit from HTMLElement or HTMLSpanElement it works!我正在尝试将影子 dom 附加到此,但它没有附加并给出错误 DOMExpection operation is not supported 但是当从 HTMLElement 或 HTMLSpanElement 继承时它可以工作! So question is can i attach shadow dom to this when inherit from HTMLButtonElement if yes then how else not why!所以问题是当从 HTMLButtonElement 继承时我可以附加影子 dom 吗? here is my code :-这是我的代码:-
class Home_Button extends HTMLButtonElement {
constructor() {
super();
this._dom = this.attachShadow({ mode: "open" });
this.createButton();
}
createButton() {
this.classList.add("contents");
const style = document.createElement("style");
style.textContent = `
.sentToHome{
margin: 1%;
padding: 1%;
border-radius: 5px;
border: 1px solid black;
}
.homeLink{
text-decoration: none;
color: green;
}
`;
const anchor = document.createElement("a");
anchor.innerText = "<< Home";
anchor.setAttribute("href", "/");
anchor.setAttribute("class", "homeLink");
const button = document.createElement("button");
button.setAttribute("class", "sentToHome");
button.appendChild(anchor);
this._dom.append(style, button);
}
}
customElements.define("simple-btn", Home_Button, { extends: "button" });
const sentToHomeBtn = new Home_Button();
document.body.appendChild(sentToHomeBtn);
This will never work in Safari, because Apple has, since 2016, stated they will never implement Customized Built-In Elements, they have only implemented extends HTMLElement
这在 Safari 中永远不会起作用,因为自 2016 年以来,Apple 已经声明他们永远不会实现自定义内置元素,他们只实现了extends HTMLElement
Trigger createButton
from the connectedCallback
;从connectedCallback
触发createButton
; you can't do DOM operations in the constructor
(besides shadowDOM content) because the element ( this
) doesn't exist in the DOM yet.您不能在constructor
中执行 DOM 操作(除了 shadowDOM 内容),因为元素 ( this
) 尚不存在于 DOM 中。
Also note this._dom
isn't required, you get this.shadowRoot
for free from attachShadow()
另请注意this._dom
不是必需的,您可以从attachShadow()
免费获得this.shadowRoot
To be clear this.classList
is the problem要清楚this.classList
是问题所在
Well, @danny-365csi-engelman is also right but I found this answer.好吧, @danny-365csi-engelman也是对的,但我找到了这个答案。
According to the answer we can attach shadow dom on few elements and button does not exits in those elements.根据答案,我们可以在少数元素上附加阴影 dom,并且按钮不会在这些元素中退出。
I just inherit from HTMLElement class instead of HTMLButtonElement class.我只是从HTMLElement类而不是HTMLButtonElement类继承。 After that everything works fine!.之后一切正常!
If you want to check current source code go here.如果你想检查当前的源代码,请到这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.