From fb769838d655c3e6d28afdb3236ab9f3d9712d10 Mon Sep 17 00:00:00 2001 From: Cor <83723320+logic-finder@users.noreply.github.com> Date: Thu, 20 Jan 2022 09:58:58 +0900 Subject: [ko] Translation done of `Using shadow DOM` document (#3576) * from html to md * translate/modify the below file and add pictures. Using shadow DOM --- .../using_shadow_dom/dom-screenshot.png | Bin 0 -> 14878 bytes .../web/web_components/using_shadow_dom/index.html | 230 -------------------- .../web/web_components/using_shadow_dom/index.md | 237 +++++++++++++++++++++ .../web_components/using_shadow_dom/shadowdom.svg | 1 + 4 files changed, 238 insertions(+), 230 deletions(-) create mode 100644 files/ko/web/web_components/using_shadow_dom/dom-screenshot.png delete mode 100644 files/ko/web/web_components/using_shadow_dom/index.html create mode 100644 files/ko/web/web_components/using_shadow_dom/index.md create mode 100644 files/ko/web/web_components/using_shadow_dom/shadowdom.svg diff --git a/files/ko/web/web_components/using_shadow_dom/dom-screenshot.png b/files/ko/web/web_components/using_shadow_dom/dom-screenshot.png new file mode 100644 index 0000000000..bab9f5796e Binary files /dev/null and b/files/ko/web/web_components/using_shadow_dom/dom-screenshot.png differ diff --git a/files/ko/web/web_components/using_shadow_dom/index.html b/files/ko/web/web_components/using_shadow_dom/index.html deleted file mode 100644 index 7d82820b76..0000000000 --- a/files/ko/web/web_components/using_shadow_dom/index.html +++ /dev/null @@ -1,230 +0,0 @@ ---- -title: Using shadow DOM -slug: Web/Web_Components/Using_shadow_DOM -tags: - - API - - DOM - - Guide - - Web Components - - shadow - - shadow dom - - 쉐도우 돔 - - 웹 컴포넌트 - - 웹컴포넌트 -translation_of: Web/Web_Components/Using_shadow_DOM ---- -
{{DefaultAPISidebar("Web Components")}}
- -

웹 컴포넌트의 중요한 측면은 캡슐화입니다. 마크업 구조, 스타일 그리고 동작을 페이지 내의 다른 코드와
- 분리하고 숨긴채로 유지하여 서로 충돌하지 않으며, 코드가 좋고 깨끗하게 되도록 하는 중요한 측면입니다.
- Shadow DOM API 는 이러한 캡슐화의 핵심이며, 숨겨지고 분리된 DOM 을 엘리먼트에 달 수 있는
- 방법입니다. 현재 문서는 Shadow DOM 의 기본적인 사용을 다루고 있습니다.

- -
-

Note: Shadow DOM 은 Firefox (63 and onwards), Chrome, Opera, and Safari 에서 기본으로 지원되고 있습니다.  새로운 Chromium 기반의 Edge (75 and onwards) 또한 지원하고 있습니다. 그러나 구버전의 Edge 는 지원하지 않습니다.

-
- -

High-level view

- -

This article assumes you are already familiar with the concept of the DOM (Document Object Model) — a tree-like structure of connected nodes that represents the different elements and strings of text appearing in a markup document (usually an HTML document in the case of web documents). As an example, consider the following HTML fragment:

- -
<!DOCTYPE html>
-<html>
-  <head>
-    <meta charset="utf-8">
-    <title>Simple DOM example</title>
-  </head>
-  <body>
-      <section>
-        <img src="dinosaur.png" alt="A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.">
-        <p>Here we will add a link to the <a href="https://www.mozilla.org/">Mozilla homepage</a></p>
-      </section>
-  </body>
-</html>
- -

This fragment produces the following DOM structure:

- -

- -

Shadow DOM allows hidden DOM trees to be attached to elements in the regular DOM tree — this shadow DOM tree starts with a shadow root, underneath which can be attached to any elements you want, in the same way as the normal DOM.

- -

- -

There are some bits of shadow DOM terminology to be aware of:

- - - -

You can affect the nodes in the shadow DOM in exactly the same way as non-shadow nodes — for example appending children or setting attributes, styling individual nodes using element.style.foo, or adding style to the entire shadow DOM tree inside a {{htmlelement("style")}} element. The difference is that none of the code inside a shadow DOM can affect anything outside it, allowing for handy encapsulation.

- -

Note that the shadow DOM is not a new thing by any means — browsers have used it for a long time to encapsulate the inner structure of an element. Think for example of a {{htmlelement("video")}} element, with the default browser controls exposed. All you see in the DOM is the <video> element, but it contains a series of buttons and other controls inside its shadow DOM. The shadow DOM spec has made it so that you are allowed to actually manipulate the shadow DOM of your own custom elements.

- -

Basic usage

- -

You can attach a shadow root to any element using the {{domxref("Element.attachShadow()")}} method. This takes as its parameter an options object that contains one option — mode — with a value of open or closed:

- -
let shadow = elementRef.attachShadow({mode: 'open'});
-let shadow = elementRef.attachShadow({mode: 'closed'});
- -

open means that you can access the shadow DOM using JavaScript written in the main page context, for example using the {{domxref("Element.shadowRoot")}} property:

- -
let myShadowDom = myCustomElem.shadowRoot;
- -

If you attach a shadow root to a custom element with mode: closed set, you won't be able to access the shadow DOM from the outside — myCustomElem.shadowRoot returns null. This is the case with built in elements that contain shadow DOMs, such as <video>.

- -
-

Note: As this blog post shows, it is actually fairly easy to work around closed shadow DOMs, and the hassle to completely hide them is often more than it's worth.

-
- -

If you are attaching a shadow DOM to a custom element as part of its constructor (by far the most useful application of the shadow DOM), you would use something like this:

- -
let shadow = this.attachShadow({mode: 'open'});
- -

When you've attached a shadow DOM to an element, manipulating it is a matter of just using the same DOM APIs as you use for the regular DOM manipulation:

- -
var para = document.createElement('p');
-shadow.appendChild(para);
-// etc.
- -

Working through a simple example

- -

Now let's walk through a simple example to demonstrate the shadow DOM in action inside a custom element — <popup-info-box> (see a live example also). This takes an image icon and a text string, and embeds the icon into the page. When the icon is focused, it displays the text in a pop up information box to provide further in-context information. To begin with, in our JavaScript file we define a class called PopUpInfo, which extends HTMLElement:

- -
class PopUpInfo extends HTMLElement {
-  constructor() {
-    // Always call super first in constructor
-    super();
-
-    // write element functionality in here
-
-    ...
-  }
-}
- -

Inside the class definition we define the element's constructor, which defines all the functionality the element will have when an instance of it is instantiated.

- -

Creating the shadow root

- -

We first attach a shadow root to the custom element:

- -
// Create a shadow root
-var shadow = this.attachShadow({mode: 'open'});
- -

Creating the shadow DOM structure

- -

Next, we use some DOM manipulation to create the element's internal shadow DOM structure:

- -
// Create spans
-var wrapper = document.createElement('span');
-wrapper.setAttribute('class','wrapper');
-var icon = document.createElement('span');
-icon.setAttribute('class','icon');
-icon.setAttribute('tabindex', 0);
-var info = document.createElement('span');
-info.setAttribute('class','info');
-
-// Take attribute content and put it inside the info span
-var text = this.getAttribute('text');
-info.textContent = text;
-
-// Insert icon
-var imgUrl;
-if(this.hasAttribute('img')) {
-  imgUrl = this.getAttribute('img');
-} else {
-  imgUrl = 'img/default.png';
-}
-var img = document.createElement('img');
-img.src = imgUrl;
-icon.appendChild(img);
-
- -

Styling the shadow DOM

- -

After that we create a {{htmlelement("style")}} element and populate it with some CSS to style it:

- -
// Create some CSS to apply to the shadow dom
-var style = document.createElement('style');
-
-style.textContent = `
-.wrapper {
-  position: relative;
-}
-
-.info {
-  font-size: 0.8rem;
-  width: 200px;
-  display: inline-block;
-  border: 1px solid black;
-  padding: 10px;
-  background: white;
-  border-radius: 10px;
-  opacity: 0;
-  transition: 0.6s all;
-  position: absolute;
-  bottom: 20px;
-  left: 10px;
-  z-index: 3;
-}
-
-img {
-  width: 1.2rem;
-}
-
-.icon:hover + .info, .icon:focus + .info {
-  opacity: 1;
-}`;
-
-
- -

Attaching the shadow DOM to the shadow root

- -

The final step is to attach all the created elements to the shadow root:

- -
// attach the created elements to the shadow dom
-shadow.appendChild(style);
-shadow.appendChild(wrapper);
-wrapper.appendChild(icon);
-wrapper.appendChild(info);
- -

Using our custom element

- -

Once the class is defined, using the element is as simple as defining it, and putting it on the page, as explained in Using custom elements:

- -
// Define the new element
-customElements.define('popup-info', PopUpInfo);
- -
<popup-info img="img/alt.png" text="Your card validation code (CVC) is an extra
-                                    security feature — it is the last 3 or 4
-                                    numbers on the back of your card.">
- -
-

Internal versus external styles

- -

In the above example we apply style to the Shadow DOM using a {{htmlelement("style")}} element, but it is perfectly possible to do it by referencing an external stylesheet from a {{htmlelement("link")}} element instead.

- -

For example, take a look at this code from our popup-info-box-external-stylesheet example (see the source code):

- -
// Apply external styles to the shadow dom
-const linkElem = document.createElement('link');
-linkElem.setAttribute('rel', 'stylesheet');
-linkElem.setAttribute('href', 'style.css');
-
-// Attach the created element to the shadow dom
-shadow.appendChild(linkElem);
- -

Note that {{htmlelement("link")}} elements do not block paint of the shadow root, so there may be a flash of unstyled content (FOUC) while the stylesheet loads.

- -

Many modern browsers implement an optimization for {{htmlelement("style")}} tags either cloned from a common node or that have identical text, to allow them to share a single backing stylesheet. With this optimization the performance of external and internal styles should be similar.

- -

See also

- - -
diff --git a/files/ko/web/web_components/using_shadow_dom/index.md b/files/ko/web/web_components/using_shadow_dom/index.md new file mode 100644 index 0000000000..603024ab9c --- /dev/null +++ b/files/ko/web/web_components/using_shadow_dom/index.md @@ -0,0 +1,237 @@ +--- +title: shadow DOM 사용하기 +slug: Web/Web_Components/Using_shadow_DOM +tags: + - API + - DOM + - Guide + - Web Components + - shadow dom +translation_of: Web/Web_Components/Using_shadow_DOM +--- +{{DefaultAPISidebar("Web Components")}} + +웹 컴포넌트의 중요한 측면은 캡슐화입니다. 캡슐화를 통해 마크업 구조, 스타일, 동작을 숨기고 페이지의 다른 코드로부터의 분리하여 각기 다른 부분들이 충돌하지 않게 하고, 코드가 깔끔하게 유지될 수 있게 합니다. Shadow DOM API는 캡슐화의 핵심 파트이며, 숨겨진 분리된 DOM을 요소에 부착하는 방법을 제공합니다. 이 문서는 Shadow DOM 사용의 기본을 다룹니다. + +> **참고:** Shadow DOM은 Firefox (63 이상), Chrome, Opera, Safari에서 기본으로 지원됩니다. 새로운 Chromium 기반의 Edge (79 이상) 또한 Shadow DOM을 지원하나 구버전 Edge는 그렇지 않습니다. + +## 중요 내용 보기 + +이 문서는 여러분이 이미 [DOM (Document Object Model)](/en-US/docs/Web/API/Document_Object_Model/Introduction)의 개념에 익숙하다고 가정합니다. DOM이란 마크업 문서에서 나타나는 여러 가지 요소들과 텍스트 문자열을 나타내는 연결된 노드들의 트리같은 구조입니다 (웹 문서의 경우 보통 HTML 문서). 예제로서, 다음의 HTML fragment를 고려해 보세요. + +```html + + + + + Simple DOM example + + +
+ A red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth. +

Here we will add a link to the Mozilla homepage

+
+ + +``` + +이 fragment는 다음의 DOM 구조를 생성합니다. + +![](dom-screenshot.png) + +_Shadow_ DOM은 숨겨진 DOM 트리가 통상적인 DOM 트리에 속한 요소에 부착될 수 있게 합니다. 이 shadow DOM 트리는 shadow root로부터 시작되어 원하는 모든 요소의 안에 부착될 수 있으며, 그 방법은 일반 DOM과 같습니다. + +![document, shadow root, shadow host의 상호 작용을 보여주는 SVG 버전의 그림.](shadowdom.svg) +Flattened Tree (for rendering): (렌더링을 위해) 평평해진 트리 + +알아야 할 조금의 shadow DOM 용어가 있습니다. + +- **Shadow host**: shadow DOM이 부착되는 통상적인 DOM 노드. +- **Shadow tree**: shadow DOM 내부의 DOM 트리. +- **Shadow boundary**: shadow DOM이 끝나고, 통상적인 DOM이 시작되는 장소. +- **Shadow root**: shadow 트리의 root 노드. + +비(非) shadow 노드와 정확히 같은 방법으로 shadow DOM 내의 노드에 영향을 미칠 수 있습니다. 예를 들자면 children을 append하거나, 특성을 설정하거나, element.style.foo를 사용해 각 노드를 꾸민다거나, {{htmlelement("style")}} 요소 내부에 있는 전체 shadow DOM 트리에 스타일을 추가하는 것이 있습니다. 차이는 shadow DOM 내부의 코드 중 아무 것도 shadow DOM 외부의 모든 것에 영향을 주지 않는다는 점인데, 이는 편리한 캡슐화를 가능케 합니다. + +shadow DOM이 어떤 방법으로든 새로운 것이 아니라는 것에 주목하세요. 브라우저들은 이것을 긴 시간동안 사용해오며 요소의 내부 구조를 캡슐화했습니다. 예를 들어 기본 브라우저 컨트롤이 노출된 {{htmlelement("video")}} 요소를 생각해 보세요. DOM에서 보이는 모든 것은 `