主页 > 前端 > javascript >
来源:未知 时间:2024-03-11 17:49 作者:小飞侠 阅读:次
[导读] js创建自定义dom对象并设置只读(html可以看js无法访问) //创建一个自定义元素MyReadOnlyTitlecustomElements.define(my-read-only-title,classextendsHTMLElement{constructor(){super();//创建ShadowDOMconstshadowRoot=this....
|
js创建自定义dom对象并设置只读(html可以看js无法访问)
// 创建一个自定义元素 MyReadOnlyTitle
customElements.define('my-read-only-title', class extends HTMLElement {
constructor() {
super();
// 创建 Shadow DOM
const shadowRoot = this.attachShadow({mode: 'open'});
// 创建一个 <h1> 元素作为标题
const h1 = document.createElement('h1');
h1.textContent = this.textContent;
// 将 <h1> 元素添加到 Shadow DOM 中
shadowRoot.appendChild(h1);
// 禁止通过 JavaScript 修改内容
Object.defineProperty(this, 'textContent', {
get() {
return '';
},
set() {
// 禁止设置内容
console.warn('Setting textContent on a MyReadOnlyTitle element has no effect.');
}
});
}
});
// 创建一个自定义元素 MyCustomTag
customElements.define('my-custom-tag', class extends HTMLElement {
constructor() {
super();
// 创建 Shadow DOM
const shadowRoot = this.attachShadow({mode: 'closed'});
// 创建一个 <span> 元素作为内容的容器
const content = document.createElement('span');
content.textContent = this.textContent;
// 将内容添加到 Shadow DOM 中
shadowRoot.appendChild(content);
}
}); |
自学PHP网专注网站建设学习,PHP程序学习,平面设计学习,以及操作系统学习
京ICP备14009008号-1@版权所有www.zixuephp.com
网站声明:本站所有视频,教程都由网友上传,站长收集和分享给大家学习使用,如由牵扯版权问题请联系站长邮箱904561283@qq.com