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>
相关推荐
Southern Wind6 分钟前
Vue 3 多实例 + 缓存复用:理念及实践
前端·javascript·vue.js·缓存·html
HuangYongbiao27 分钟前
Rspack 原理:webpack,我为什么不要你
前端
yinuo31 分钟前
前端项目开发阶段崩溃?试试这招“Node 内存扩容术”,立马复活!
前端
前端鳄鱼崽33 分钟前
【react-native-inspector】全网唯一开源 react-native 点击组件跳转到编辑器
前端·react native·react.js
用户984022766791833 分钟前
【React.js】渐变环形进度条
前端·react.js·svg
90后的晨仔34 分钟前
Webpack完全指南:从零到一彻底掌握前端构建工具
前端·vue.js
Holin_浩霖35 分钟前
JavaScript 语言革命:ES6+ 现代编程范式深度解析与工程实践
前端
前端拿破轮41 分钟前
从0到1搭一个monorepo项目(一)
前端·javascript·git
m0_741412241 小时前
大文件上传与文件下载
前端
wu_jing_sheng01 小时前
Python中使用HTTP 206状态码实现大文件下载的完整指南
开发语言·前端·python