gpt4 book ai didi

javascript - 使用javascript在自定义元素中设置主机样式

转载 作者:行者123 更新时间:2023-11-28 08:48:21 25 4
gpt4 key购买 nike

我写了下面的代码来获得一个带有文本和按钮的阴影 DOM,文本和按钮的样式都正确,而主机背景的样式却很奇怪,

代码是:

 // 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 = '\
<style>\
:host { \
border: 2px dashed red;\
text-align: left;\
font-size: 28px;\
background: blue;\
}\
h3 { color: red; }\
button { color: green; }\
</style>\
<h3>Shadow DOM</h3>\
<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";
alert("All: button, text and host should be change");
});
};

输出在附件中。

请帮忙。

enter image description here

最佳答案

我能够使用 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;}

可以看到输出here:

关于javascript - 使用javascript在自定义元素中设置主机样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27494513/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com