@todojs/

12.css-host()

HTML, CSS, JS

No description

fork
loading
Files
  • index.html
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSS and Shadow DOM (:host(selector))</title>
</head>
<body>
<div id="test" class="alert" hidden></div>
<p>
  <button id="show">show/hide element</button>
  <button id="change">change class .alert</button>
</p>
<script>
  const div = document.querySelector ('#test');
  div.attachShadow ({mode : 'open'});

  const style     = document.createElement ('style');
  style.innerHTML =
    ':host {' +
    '  display         : table-cell;' +
    '  text-align      : center;' +
    '  height          : 5em;' +
    '  width           : 10em;' +
    '  vertical-align  : middle;' +
    '  background-color: lightgreen;' +
    '  border          : 1px solid darkgreen;' +
    '}' +
    ':host([hidden]) { ' +
    '  display: none ' +
    '}' +
    ':host(.alert) button {' +
    '  color: red;' +
    '}';

  const button = document.createElement ('button');
  button.classList.add ('button');
  button.innerHTML = 'shadow context';

  div.shadowRoot.appendChild (style);
  div.shadowRoot.appendChild (button);

  document.querySelector ('#show').addEventListener ('click', function () {
    div.hasAttribute ('hidden') ?
      div.removeAttribute ('hidden') :
      div.setAttribute ('hidden', '')
  });

  document.querySelector ('#change').addEventListener ('click', function () {
    div.classList.toggle ('alert');
  });
</script>
</body>
</html>
result
console