美文网首页
ShadowDOM DEMO

ShadowDOM DEMO

作者: _____西班木有蛀牙 | 来源:发表于2018-11-01 14:16 被阅读14次
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>ShadowDOM - test</title>
  <style>
    #div { width: 300px;height: 50px;border: 1px solid #666;padding: 15px; }
  </style>
</head>
<body>
  <div id="div">这里是不显示出来的,如果你看到了,说明浏览器不支持ShadowDOM</div>
  <button>点我点我</button>
  <script>
  function createShadowDOM(elem) {
    var root = elem.createShadowRoot();
    root.appendChild(createStyle());
    root.appendChild(createInputDiv("姓名","name"));
  }

  function createStyle() {
    var style = document.createElement('style');
    style.textContent = 'div.input-div { height: 30px; width: 250px; }' +
    'font.input-font { line-height: 30px;font-size: 16px;color: #495A80; margin-right: 10px;}'+
    'span.input-area {width: 200px;height: 25px;line-height: 25px;padding-left: 5px;display:inline-block;color: #666;font-size: 16px;border: 1px solid #999;border-radius: 3px;}';
    return style;
  }

  function createInputDiv(font, name) {
    var inputDiv = document.createElement('div');
    inputDiv.className = 'input-div';
    inputDiv.innerHTML = "<font class='input-font'>" + font + "</font><span class='input-area' contentEditable='true' id=" + name + "></span>";
    return inputDiv;
  }

  createShadowDOM(document.querySelector("#div"));

  document.querySelector('button').addEventListener('click', function() {
    alert(document.querySelector('#div').shadowRoot.querySelector('#name').innerHTML);
  })
  </script>
</body>
</html>

相关文章

网友评论

      本文标题:ShadowDOM DEMO

      本文链接:https://www.haomeiwen.com/subject/ykhxxqtx.html