Element.attachShadow() method attaches a shadow DOM tree to the specified element and returns a reference to its ShadowRoot .

Elements you can attach a shadow to

Note that you can't attach a shadow root to every type of element. There are some that can't have a shadow DOM for security reasons (for example <a> ), and more besides. The following is a list of elements you can attach a shadow root to:

句法

var shadowroot = element.attachShadow(shadowRootInit);
					

参数

shadowRootInit
A ShadowRootInit dictionary, which can contain the following fields:
mode

A string specifying the encapsulation mode for the shadow DOM tree. This can be one of:

  • open : Elements of the shadow root are accessible from JavaScript outside the root, for example using Element.shadowRoot :
    element.shadowRoot; // Returns a ShadowRoot obj
    										
  • closed : Denies access to the node(s) of a closed shadow root from JavaScript outside it:
    element.shadowRoot; // Returns null
    										
delegatesFocus
A boolean that, when set to true , specifies behavior that mitigates custom element issues around focusability. When a non-focusable part of the shadow DOM is clicked, the first focusable part is given focus, and the shadow host is given any available :focus styling.

返回值

返回 ShadowRoot 对象。

异常

异常 解释
InvalidStateError The element you are trying to attach to is already a shadow host.
NotSupportedError You are trying to attach a shadow root to an element outside the HTML namespace, or the element cannot have a shadow attached to it (see above).

范例

The following example is taken from our word-count-web-component demo ( see it live also ). You can see that we use attachShadow() in the middle of the code to create a shadow root, which we then attach our custom element's contents to.

// Create a class for the element
class WordCount extends HTMLParagraphElement {
  constructor() {
    // Always call super first in constructor
    super();
    // count words in element's parent element
    var wcParent = this.parentNode;
    function countWords(node){
      var text = node.innerText || node.textContent
      return text.trim().split(/\s+/g).length;
    }
    var count = 'Words: ' + countWords(wcParent);
    // Create a shadow root
    var shadow = this.attachShadow({mode: 'open'});
    // Create text node and add word count to it
    var text = document.createElement('span');
    text.textContent = count;
    // Append it to the shadow root
    shadow.appendChild(text);
    // Update count when element content changes
    setInterval(function() {
      var count = 'Words: ' + countWords(wcParent);
      text.textContent = count;
    }, 200)
  }
}
// Define the new element
customElements.define('word-count', WordCount, { extends: 'p' });
							

规范

规范 状态 注释
DOM
The definition of 'attachShadow()' in that specification.
实时标准

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
attachShadow Chrome 53 Edge 79 Firefox 63
63
不支持 59 — 63 Disabled
Disabled ). To change preferences in Firefox, visit
IE No Opera 40 Safari 10 WebView Android 53 Chrome Android 53 Firefox Android 63
63
不支持 59 — 63 Disabled
Disabled ). To change preferences in Firefox, visit
Opera Android 41 Safari iOS 10 Samsung Internet Android 6.0
delegatesFocus option of ShadowRootInit 字典。 非标 Chrome Yes Edge 79 Firefox No IE No Opera ? Safari ? WebView Android Yes Chrome Android Yes Firefox Android No Opera Android ? Safari iOS ? Samsung Internet Android Yes

图例

完整支持

完整支持

不支持

不支持

兼容性未知 ?

兼容性未知

实验。期望将来行为有所改变。

实验。期望将来行为有所改变。

非标。预期跨浏览器支持较差。

非标。预期跨浏览器支持较差。

用户必须明确启用此特征。

用户必须明确启用此特征。

元数据

  • 最后修改:
  1. 元素
  2. 特性
    1. accessKey
    2. 属性
    3. childElementCount
    4. children
    5. classList
    6. className
    7. clientHeight
    8. clientLeft
    9. clientTop
    10. clientWidth
    11. currentStyle
    12. firstElementChild
    13. id
    14. innerHTML
    15. lastElementChild
    16. localName
    17. 名称
    18. namespaceURI
    19. nextElementSibling
    20. onfullscreenchange
    21. onfullscreenerror
    22. openOrClosedShadowRoot
    23. outerHTML
    24. part
    25. prefix
    26. previousElementSibling
    27. runtimeStyle
    28. scrollHeight
    29. scrollLeft
    30. scrollLeftMax
    31. scrollTop
    32. scrollTopMax
    33. scrollWidth
    34. shadowRoot
    35. slot
    36. tabStop
    37. tagName
  3. 方法
    1. after()
    2. animate()
    3. append()
    4. attachShadow()
    5. before()
    6. closest()
    7. computedStyleMap()
    8. createShadowRoot()
    9. getAnimations()
    10. getAttribute()
    11. getAttributeNames()
    12. getAttributeNode()
    13. getAttributeNodeNS()
    14. getAttributeNS()
    15. getBoundingClientRect()
    16. getClientRects()
    17. getElementsByClassName()
    18. getElementsByTagName()
    19. getElementsByTagNameNS()
    20. hasAttribute()
    21. hasAttributeNS()
    22. hasAttributes()
    23. hasPointerCapture()
    24. insertAdjacentElement()
    25. insertAdjacentHTML()
    26. insertAdjacentText()
    27. matches()
    28. msZoomTo()
    29. prepend()
    30. querySelector()
    31. querySelector()
    32. querySelectorAll()
    33. querySelectorAll()
    34. releasePointerCapture()
    35. remove()
    36. removeAttribute()
    37. removeAttributeNode()
    38. removeAttributeNS()
    39. replaceChildren()
    40. replaceWith()
    41. requestFullscreen()
    42. requestPointerLock()
    43. scroll()
    44. scrollBy()
    45. scrollIntoView()
    46. scrollIntoViewIfNeeded()
    47. scrollTo()
    48. setAttribute()
    49. setAttributeNode()
    50. setAttributeNodeNS()
    51. setAttributeNS()
    52. setCapture()
    53. setPointerCapture()
    54. toggleAttribute()
  4. 事件
    1. afterscriptexecute
    2. auxclick
    3. blur
    4. click
    5. compositionend
    6. compositionstart
    7. compositionupdate
    8. contextmenu
    9. copy
    10. cut
    11. dblclick
    12. DOMActivate
    13. DOMMouseScroll
    14. error
    15. focus
    16. focusin
    17. focusout
    18. fullscreenchange
    19. fullscreenerror
    20. gesturechange
    21. gestureend
    22. gesturestart
    23. keydown
    24. keypress
    25. keyup
    26. mousedown
    27. mouseenter
    28. mouseleave
    29. mousemove
    30. mouseout
    31. mouseover
    32. mouseup
    33. mousewheel
    34. MozMousePixelScroll
    35. msContentZoom
    36. MSGestureChange
    37. MSGestureEnd
    38. MSGestureHold
    39. MSGestureStart
    40. MSGestureTap
    41. MSInertiaStart
    42. MSManipulationStateChanged
    43. overflow
    44. paste
    45. scroll
    46. select
    47. show
    48. touchcancel
    49. touchend
    50. touchmove
    51. touchstart
    52. underflow
    53. webkitmouseforcechanged
    54. webkitmouseforcedown
    55. webkitmouseforceup
    56. webkitmouseforcewillbegin
    57. wheel
  5. 继承:
    1. 节点
    2. EventTarget

版权所有  © 2014-2026 乐数软件    

工业和信息化部: 粤ICP备14079481号-1