直接上代码 说明javascript代码直接嵌入在html里
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html charset=utf-8"/>
<title>用影子DOM创建一个对话框
</title>
<style>
//这个对话框样式对模版里面的div没有什么作用
.dialog-container
{
display: none;
position: fixed;
left: 50%;
top:50%;
transform: translate(-50%,-50%);
padding: 20px;
border: 1px solid #ccc;
z-index:999;
}
.dialog-open
{
display: block;
}
</style>
</head>
<body>
//这里是自定义的元素<dialog-component>
<dialog-component>这里是内容</dialog-component>
</body>
<script type="text/javascript">
//生成自定义元素的类,继承于HTMLElement
class DialogComponent extends HTMLElement
{
constructor()
{
super();//继承父元素
this.attachShadow({mode:'open'});//设计DOM影子元素模式,获得影子DOM的实例,open主要作用就是使用shadowRoot属性可以在html上获得元素的引用
//设置一个公共属性
this.open=true;
}
//自定义元素实例添加到dom中时调用
connectedCallback(){
this.render();
}
render(){
//自定义元素中的内容模版,分别设置他们的CSS样式
const template=`
<div class="dialog-container">
<slot></slot>
<button>关闭</button>
</div>
<style>
div{
border:1px solid red;
width:200px;
height:150px;
}
button{
position:relative;
top:120px;
left:20px;
transform:translateX(-50%);
}
</style>
`;
//添加进自定义元素中
this.shadowRoot.innerHTML=template;
//点击关闭按钮时
this.shadowRoot.querySelector('.dialog-container').addEventListener('click',(e)=>{
if(e.target.tagName==='BUTTON')
{
console.log('1');
this.closeDialog();
}
});
}
//关闭自定义元素
closeDialog(){
this.shadowRoot.querySelector('.dialog-container').classList.remove('dialog-open');
this.shadowRoot.querySelector('.dialog-container').style.display='none';
}
//打开对话框
openDialog(){
this.shadowRoot.querySelector('.dialog-container').classList.add('dialog-open');
//console.log(this.shadowRoot);
}
//设置监控自定义元素的属性
static get observedAttributes(){
return ['open'];//被监控属性open
}
//当被监控自定义元素的属性值发生改变时做出判断
attributeChangedCallback(name,oldVal,newVal)
{
if(name==='open' && newVal==='true')
{
this.openDialog();
}
if(name==='open' && newVal==='false')
{
this.closeDialog();
}
}
set open(val)
{
this.setAttribute('open',val);
}
get open()
{
return this.getAttribute('open');
}
msg()
{
console.log('这是一个信息');
}
}
//创建自定义元素
customElements.define('dialog-component',DialogComponent);
</script>
<script>
document.addEventListener('DOMContentLoaded',()=>{
const dialog=document.querySelector('dialog-component');
dialog.openDialog();//直接用元素调用类中的方法
dialog.setAttribute('open','true');//改变监控open属性的值
/*
setTimeout(()=>{
dialog.setAttribute('open','false');
},3000);
*/
dialog.msg();//测试自定义元素是否可以直接调用类中的方法
});
</script>
</html>