html自定义元素过程

  1. 使用customElements.define()方法创建,方法传递两个参数,第一个自定义元素名字,第二个HTMLElement扩展子类
  2. 浏览器自动调用自定义元素的‘生命期方法’,当自定义元素插入文档时会调用connectedCallback()方法。还有一个disconnectedCallback()方法 在元素从文档中移除时调用,但用的不多
  3. 定义静态属性observedAttributes,其值是一个属性名数组,当元素使用其定义的属性名,浏览器会调用attributeChangedCallback()方法,该方法传入属性名、旧值、新值。
  4. 定义js获取元素属性和修改元素属性方法,让元素暴露为js属性
        //行内圆圈自定义
        //customElements.define()两个参数第一个是自定元素名,第二扩展类
        //使用customElements.define定义 HTMLElement扩展类InlineCircle 
        
        customElements.define('inline-circle', class InlineCircle extends HTMLElement {

            //插入文档时调用connectedCallback()函数 在函数内设置元素样式
            connectedCallback() {
                this.style.display = 'inline-block'
                this.style.border = '1px solid black'
                this.style.borderRadius = '50%'
                this.style.transform = 'translateY(10%)'

                //默认尺寸
                if (!this.style.width) {
                    this.style.width = '.8em'
                    this.style.height = '.8em'
                }
            }

            //定义静态observedAttributes属性,值为属性名数组
            //定义在observedAttribues属性,在修改其值时浏览器或调用attributeChangedCallback()函数
            static get observedAttributes() { return ['diameter', 'color'] }

            //attributeChangedCallback()三个参数 要修改的属性名 属性原值 属性新值
            attributeChangedCallback(name, oldValue, newValue) {
                switch (name) {
                    case 'diameter':
                        this.style.width = newValue
                        this.style.height = newValue
                        break
                    case 'color':
                        this.style.backgroundColor = newValue
                        break
                }
            }

            // 使用js获得修改属性的方法 同样使用这些方法会触发attributeChangedCallback()函数
            get diameter() { return this.getAttribute('diameter') }
            set diameter(diameter) { return this.setAttribute('diameter', diameter) }
            get color() { return this.getAttribute('color') }
            set color(color) { return this.setAttribute('color', color) }
        })  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值