| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/zh-CN/docs/Web/API/ShadowRoot | [Back] [Original] |
Get to know MDN better
ShadowRoot.delegatesFocus boolean shadow delegatesFocus (see Element.attachShadow())
ShadowRoot.host ShadowRoot DOM
ShadowRoot.innerHTMLShadowRoot DOM
ShadowRoot.mode ShadowRoot open closed shadow root JavaScript <video> JavaScript
ShadowRoot DocumentOrShadowRoot mixin Chrome ; Document
ShadowRoot DocumentOrShadowRoot mixin Chrome ; Document
DocumentOrShadowRoot.getSelection()DocumentOrShadowRoot.elementFromPoint()DocumentOrShadowRoot.elementsFromPoint()Array
DocumentOrShadowRoot.caretPositionFromPoint() CaretPosition DOM
Inside the <custom-square> element's class definition we include some life cycle callbacks that make a call to an external function, upateStyle(), which actually applies the size and color to the element. You'll see that we are passing it this (the custom element itself) as a parameter.
connectedCallback() {
console.log('Custom square element added to page.');
updateStyle(this);
}
attributeChangedCallback(name, oldValue, newValue) {
console.log('Custom square element attributes changed.');
updateStyle(this);
}
In the updateStyle() function itself, we get a reference to the shadow DOM using Element.shadowRoot. From here we use standard DOM traversal techniques to find the <style> element inside the shadow DOM and then update the CSS found inside it:
function updateStyle(elem) {
var shadow = elem.shadowRoot;
var childNodes = shadow.childNodes;
for (var i = 0; i < childNodes.length; i++) {
if (childNodes[i].nodeName === "STYLE") {
childNodes[i].textContent =
"div {" +
"width: " +
elem.getAttribute("l") +
"px;" +
"height: " +
elem.getAttribute("l") +
"px;" +
"background-color: " +
elem.getAttribute("c") +
";" +
"}";
}
}
}
| DOM # interface-shadowroot |
| Web Proxy Viewer | New URL | Original Page |