@todojs/

13.css-host-context()

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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CSS and Shadow DOM (:host-context(selector))</title>
  <style>
    body.dark {
      background-color: black;
      color           : white;
    }
  </style>
</head>
<body class="dark">
<div id="test" class="alert"></div>
<p>
  <button id="change">change BODY class .dart to .light</button>
</p>
<script>
  const div = document.querySelector ('#test');
  div.attachShadow ({mode : 'open'});

  const style     = document.createElement ('style');
  style.innerHTML =
    ':host-context(.dark) button {' +
    '  background-color: #555;' +
    '  color           : #C0C0C0;' +
    '  border          : 1px solid grey;' +
    '}' +
    ':host-context(.light) button {' +
    '  background-color: #F0F0F0;' +
    '  color           : #0C0C0C;' +
    '  border          : 1px solid back;' +
    '}';

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

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

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