javascript - 访问 shadow dom 属性
问题描述
所以这是我的脚本代码
class Pop extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
let currDoc = document.currentScript.ownerDocument;
let template = currDoc.querySelector('#pop-up');
let tmplNode = document.importNode(template.content, true);
let shadowRoot = this.createShadowRoot();
shadowRoot.appendChild(tmplNode);
shadowRoot.querySelector("#content").innerHTML = this.innerHTML;
}
}
window.customElements.define("pop-up", Pop);
这是我的模板
<template id="pop-up">
<style>
* {
padding: 0;
margin: 0;
}
.btn {
//styling
}
.btn:hover {
//styling
}
#box{
//styling
display: none;
}
#box h1{
//styling
}
</style>
<div id="box">
<h1> Your Shopping Cart</h1>
<text id="content"> </text>
<button class="btn" onclick="close()"> Close </button>
</div>
</template>
在我的索引文件中我有这个
<button class="btn" onclick="pop()">Show Pop</button>
<pop-up id="pop"> pop-up box</pop-up>
<script>
function pop(){
document.getElementById("pop").style.display = "block";
}
</script>
我正在尝试做一个弹出框。当我单击“显示弹出”按钮时,我想将显示属性从样式更改为从“无”到“块”。但由于某种原因,它不起作用。我是这个影子 dom 元素的新手,我真的想不通。
解决方案
很难解释此答案中的所有内容,但以下代码将为您概述解决方案的外观。
像往常一样,MDN在这里对 Web 组件和影子 dom 进行了完美的介绍
class Pop extends HTMLElement {
constructor() {
// Always call super first in constructor
super();
let template = document.getElementById('pop-up');
let templateContent = template.content;
// Create a shadow root
const shadowRoot = this.attachShadow({ mode: 'open' })
.appendChild(templateContent.cloneNode(true));
// attach close listener
this.shadowRoot.querySelector('.btn').addEventListener('click', this.close.bind(this));
}
// close pop-up
close() {
this.style.display = 'none';
}
// open pop-up
open() {
this.style.display = 'block';
}
}
window.customElements.define("pop-up", Pop);
function pop() {
// notice we are using the open method here
document.getElementById("pop").open();
}
<template id="pop-up">
<style>
:host {
display: none;
}
* {
padding: 0;
margin: 0;
}
.btn {
//styling
}
.btn:hover {
//styling
}
#box {
//styling
display: none;
}
#box h1 {
//styling
}
</style>
<div id="box">
<h1> Your Shopping Cart</h1>
<!-- Notice we are using slots -->
<slot> </slot>
<button class="btn"> Close </button>
</div>
</template>
<button class="btn" onclick="pop()">Show Pop</button>
<pop-up id="pop"> pop-up box </pop-up>
推荐阅读
- python - 有没有办法让文件立即在程序中打开而不是之后?
- javascript - react redux 为什么使用 dispatch = useDispatch()?
- codeception - 未执行任何测试 - 验收测试 Codeception
- github - 如何在 GitHub 工作流程中安排和 push/pull_request 事件?
- node.js - Express Knex req.query
- node.js - Firebase 功能:发送响应后如何最好地等待解除阻塞的承诺?
- list - 如何按属性从列表中过滤对象 - Kotlin
- node.js - 编译包含依赖项的打字稿节点 js 应用程序
- flutter - 是否有任何方法或包装让我在我的设备主页中显示特定的应用程序屏幕
- apache2.4 - 服务器证书不包含与 django 的服务器名称匹配的 ID