Web Components

Web Components标准非常重要的一个特性是,它使开发者能够将HTML页面的功能封装为custom elements(自定义标签),可以使用CustomElementRegistry来管理自定义标签

javascript 复制代码
<script>
    //1、创建自定义标签
    class NewElement extends HTMLElement {
        constructor () {
            super();
            // 在此定义自定义标签
            // 创建一个shadow根标签
            let shadow = this.attachShadow({mode: 'open'});
            // 创建我们需要的标签
            let wrapper = document.createElement('div');
            let iconBox = document.createElement('div');
            let textBox = document.createElement('div');
        
            // 为标签添加样式
            wrapper.setAttribute('class', 'wapper');
            iconBox.setAttribute('class', 'icon');
            textBox.setAttribute('class', 'text');
        
            let text = this.getAttribute('text'); // 获取标签里面传递的值
            textBox.textContent = text;
        
            let imgUrl;
            if(this.hasAttribute('img')) {
                imgUrl = this.getAttribute('img');
            } else {
                imgUrl = 'default.png'; // 设置一个默认图片
            }
            var img = document.createElement('img');
            img.src = imgUrl;
            iconBox.appendChild(img);
        
            // 书写样式
            var style = document.createElement('style');
            let lStyleStr = '.wrapper { display: flex; justify-content: center; align-items: center; width: 100%; height: 50px;}';
            lStyleStr += '.icon {margin-right: 10px; width: 50px; height: 50px;}';
            lStyleStr += '.icon img { width: 100%; height: 100%;}';
            lStyleStr += '.text { flex: 1; font-size: 14px; color: #333; line-height: 50px;}';
            style.textContent = lStyleStr;
        
            // 将样式和dom元素挂载到页面
            shadow.appendChild(style);
            shadow.appendChild(wrapper);
            wrapper.appendChild(iconBox);
            wrapper.appendChild(textBox);
        }
    }
    
    //2、注册自定义标签
    customElements.define('new-element', NewElement);    
</script>
 
 //3、使用
<body>
    <new-element img="you_picture.jpg" text="你的文字"></new-element>
</body>
相关推荐
lgbisha14 分钟前
银河麒麟入门:日志刷满终端,用 less 定位关键词并看前后几行
java·前端·less·银河麒麟
w-w0w-w1 小时前
CSRF 与 JWT 漏洞原理、攻击手法及防御机制
前端·网络·csrf
默 语1 小时前
HarmonyOS7 组件通用事件(一):四大事件总览——组件的生死、身位与存在感
服务器·前端·javascript
低代码布道师1 小时前
第06篇:用户新增——React Hook Form + Zod 搭建可复用的表单体系
前端·react.js·前端框架
前端的日常2 小时前
不花一分钱,每天白嫖 Cloudflare 的大模型接口,手把手教你接入
前端
海是岛思念的泪2 小时前
给电脑端喝水提醒工具做离线缓存:Service Worker 分层策略实战(附完整代码)
前端
牧艺2 小时前
滚动监听可以退休了:CSS Scroll-driven Animations 从原理到可上线
前端
青莲8432 小时前
SPI、AutoService、KSP、ASM:编译时与运行时各做哪一步
前端·app
打工仔折腾 AI2 小时前
智能体开发实战:Agent架构拆解与ReAct执行循环工程落地
前端·后端·python·react.js·架构·langchain·ai agent 实战
htzyl2062 小时前
升级到 TypeScript 7:哪些 tsconfig 选项会直接报错
前端·typescript