簡體   English   中英

DOM影子主機的JavaScript樣式

[英]JavaScript styling of DOM shadow host

基於對這一點的理解,我編寫了以下代碼:

主機沒有樣式!

 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文件中的UPDATE ,我稱之為:

<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;}

輸出可以在這里看到

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM