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>
相关推荐
星栈9 小时前
pnpm 12 升级实测
前端·javascript
Sirens.9 小时前
Java并发锁详解:六类锁策略与 synchronized 底层原理
java·前端·算法
特创数字科技11 小时前
一个纯本地运行的图片处理工具:压缩 / 裁剪 / 九宫格 / 圆角 / 滤镜 / 拼图 / 水印,终生使用
前端
IT_陈寒11 小时前
Vue的v-if和v-for混用居然是个天坑
前端·人工智能·后端
天衍四九-11 小时前
【无标题】
前端·spring boot·mysql·nginx·docker
广州华水科技11 小时前
2026年单北斗GNSS变形监测系统推荐榜单,解锁GNSS位移监测新高度
前端
xcyxiner12 小时前
DicomViewer24 修复编译bug(window test 失败)
前端·qt
linux_cfan12 小时前
videojs v10 源代码系列解读:34 · `createComposition`:类型安全的冲突检测
前端·安全
utmhikari13 小时前
【AI原生】借助AI之力优化个人博客前端样式
前端·css·hexo·next·个人博客·ai-native·vibe coding