DOM 影子主机的 JavaScript 样式



基于我对这一点的理解,我编写了以下代码:

主人没有风格!

 var fonixDiv = Object.create(HTMLElement.prototype);
 // Set up the element.
 fonixDiv.createdCallback = function() {
 // Create a Shadow Root
 var shadow = this.createShadowRoot();
 shadow.innerHTML = '<style>'+
  ':host { width:200px; height:200px; background: #b0c4de; }'+          // Not working
      'p{color: red;}'+                                                 // Working
      '</style>'+
      '<p>hi</p><button id="d">click</button>';
      shadow.children.d.addEventListener('click', function(e) {
        this.textContent = "you clicked me :(";
        shadow.children[1].textContent="Shadow DOM content changed";
        host.style.background = "green";                                 // working
        alert("All: button, text and host should be change");
  });
};
 // Register the new element.
 var Xfonix =document.registerElement('fonix-div', {
  prototype: fonixDiv
 });

更新在 html 文件中,我将其称为:

<fonix-div></fonix-div>

以及:

<div id='host'></div>
<script>
var host = document.querySelector('#host');
var el = new Xfonix();
host.appendChild(el);
<script>

任何帮助如何设置主机元素的样式!

小提琴来了

没有任何内容适用于主机样式,无论是宽度、高度还是背景:(

我能够使用 css 文件解决问题:

.html文件为:

<fonix-div></fonix-div>
<div id="host1"></div>

.js文件为:

// Create a new object based of the HTMLElement prototype
var fonixDiv = Object.create(HTMLElement.prototype);
// Set up the element.
fonixDiv.createdCallback = function() {
// Create a Shadow Root
var shadow = this.createShadowRoot();
    shadow.innerHTML = '<button id="d">click</button>';
       shadow.addEventListener('click', function(e) {
            console.log('1: '+this.host.dataset.disabled);
            this.host.dataset.disabled='true';   // set Attribute to the custom element
       });
       shadow.children.d.addEventListener('click', function(e) {
            this.textContent = "you clicked me :(";
            shadow.children[1].textContent="Shadow DOM content changed";
            this.disabled=true;
            alert("All: button, text and host should be change");
       });
};
// Register the new element.
var Xfonix =document.registerElement('fonix-div', {prototype: fonixDiv});
var thehost = document.querySelector('#host1');
thehost.appendChild(new Xfonix());

.css文件为:

body {background: #F7F7F7;}
fonix-div {
  display: inline-block;
  width: 200px;
  height: 200px;  
  float: left;
  margin: 0.5em;
  border-radius: 3px;
  background: #FFF;
  box-shadow: 0 1px 3px rgba(0,0,0,0.25);
  font-family: Helvetica, arial, sans-serif;
  -webkit-font-smoothing: antialiased;
    }
fonix-div:hover, fonix-div[data-disabled='true']:hover {background: red;}
fonix-div:Active {background: green;}
fonix-div[data-disabled='true'] {background: green;}
fonix-div::shadow p{color: blue;}

输出可以在这里看到:

最新更新