首页 Javascript 正文
42

Javascript创建web component

  • yiqingpeng
  • 2023-11-01
  • 0
  •  
具体的概念和使用方法请参考mdn: https://developer.mozilla.org/zh-CN/docs/Web/API/Web_components
本文的示例权当抛砖引玉。
Javascript代码:
class TimelapsingBar extends HTMLElement {
          barElement;
          constructor() {
            // 必须首先调用 super 方法
            super();

            // 元素的功能代码写在这里
            // 创建一个 shadow root
            var shadow = this.attachShadow({mode: 'open'});

            var wrapper = document.createElement('div');
            wrapper.setAttribute('class','wrapper');
            var bar = document.createElement('div');
            bar.setAttribute('class', 'bar');
            this.barElement = bar;
            wrapper.appendChild(bar);
            
            // 创建一些 CSS,并应用到 shadow dom 上
            var style = document.createElement('style');
            var height = this.getAttribute('height') || '4px';
            var bgColor = this.getAttribute('bgcolor') || '#CCC';
            var color = this.getAttribute('color') || '#056DE8';
            var reverse = this.getAttribute('reverse') !== null;
            var growing = reverse ? '0%{width:100%;} 100%{width:0;}' : '0%{width:0;} 100%{width:100%;}';
            var auto = this.getAttribute('auto') !== null;
            var loop = this.getAttribute('loop') !== null;
            
            style.textContent = '.wrapper {' + 
            '                        width:100%;height:'+height+';background:'+bgColor+';' + 
            '                    }' + 
            '                    .bar {' + 
            '                        height:' + height + ';background:'+color+';border:none;margin:0px;' + 
            '                    }' + 
            '                    @keyframes growing {' + 
            '                        ' + growing + 
            '                    }';
            shadow.appendChild(style);
            shadow.appendChild(wrapper);
            
            auto && this.go();
            
            if (loop) {
                this.barElement.addEventListener('animationend', () => {
                    this.go();
                });
            }
          }
          
          // go方法供外部调用
          go(){
            var period = this.getAttribute('period') || '20';
            this.barElement.style.animation = "";
            void this.barElement.offsetWidth; // Trigger re-render
            this.barElement.style.animation = 'growing ' +period+ 's linear';
          }
    }
    
    window.customElements.define('timelapsing-bar', TimelapsingBar);
HTML代码:
<timelapsing-bar id="p1" period="5" height="10px" auto loop></timelapsing-bar>

<timelapsing-bar id="p2" bgcolor="#273A4B" color="#2c833F" period="10" height="15px" reverse auto loop>
</timelapsing-bar>
效果图

正在加载评论...