[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/zh-CN/docs/Web/API/ShadowRoot [Back]  [Original]

ShadowRoot - Web API | MDN

MDN Web Docs

View in English Always switch to English

ShadowRoot

*

20201

*

Shadow DOM API ShadowRoot DOM DOM

Element.shadowRoot Element.attachShadow() mode open.

ShadowRoot.delegatesFocus

boolean shadow delegatesFocus (see Element.attachShadow())

ShadowRoot.host

ShadowRoot DOM

ShadowRoot.innerHTML

ShadowRoot DOM

ShadowRoot.mode

ShadowRoot open closed shadow root JavaScript <video> JavaScript

DocumentOrShadowRoot

ShadowRoot DocumentOrShadowRoot mixin Chrome ; Document

DocumentOrShadowRoot.activeElement

shadow tree Element

DocumentOrShadowRoot.styleSheets

CSSStyleSheet StyleSheetList

ShadowRoot DocumentOrShadowRoot mixin Chrome ; Document

DocumentOrShadowRoot.getSelection()

Selection

DocumentOrShadowRoot.elementFromPoint()

DocumentOrShadowRoot.elementsFromPoint()

Array

DocumentOrShadowRoot.caretPositionFromPoint()

CaretPosition DOM

life-cycle-callbacks ()

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.

js
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:

js
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