@group_wtf_npm/loading
Version:
loading加载
98 lines (94 loc) • 4.32 kB
JavaScript
/**
* 自定义元素 WtfLoading
* 用于显示加载动画的 Web Component,支持遮罩层和绝对定位。
*/
class WtfLoading extends HTMLElement {
/**
* 构造函数
* 初始化组件并创建 Shadow DOM。
*/
constructor() {
super();
// 创建 Shadow DOM,设置为开放模式
this.attachShadow({ mode: 'open' });
}
/**
* 生命周期回调:connectedCallback
* 当元素被插入到 DOM 中时调用。
* 负责渲染组件的 HTML 和样式。
*/
connectedCallback() {
// 检查是否设置了 'absolute' 属性,决定是否启用绝对定位
const absolute = this.getAttribute('absolute');
// 获取 'mask' 属性的值,用于设置遮罩层的背景
// 尝试将 'mask' 转换为浮点数,用于判断是否为透明度值
const mask = this.getAttribute('mask');
const mask_num = parseFloat(mask);
// 设置 Shadow DOM 的内部 HTML 和样式
this.shadowRoot.innerHTML = `
<style>
/* :host 选择器用于定义自定义元素的样式 */
:host {
${absolute ? 'position:absolute;z-index:100;top:50%;left:50%;width:100%;height:100%;transform:translate(-50%,-50%);' : ''}
align-content:center;text-align:center;font-size:calc(100vw / 1920 * 32);
${Number.isNaN(mask_num) ? `background:${mask};` : `background:rgba(255,255,255,${mask_num});`}
}
@media screen and (min-width: 1501px){:host{font-size:calc(100vw / 1920 * 16);}}
@media screen and (max-width: 1500px){:host{font-size:calc(100vw / 1500 * 24);}}
@media screen and (max-width: 750px){:host{font-size:calc(100vw / 750 * 32);}}
/* 加载容器样式 */
.loading_container {
padding:1em 2em;
display:inline-block;
border-radius:0.25em;
background:#fff;
}
/* 加载图标样式 */
.loading_icon {
margin-bottom:0.6em;
width:4em;
height:4em;
}
/* 第一个圆圈的动画 */
.loading_icon circle:first-child {
animation:3s loading_circle_animat infinite linear;
transform-origin:center center;
}
/* 第二个圆圈的动画 */
.loading_icon circle:last-child {
animation:1.5s loading_circle_animat infinite linear;
transform-origin:center center;
}
/* 加载消息样式 */
.loading_msg {
color:#666;
}
/* 定义旋转动画 */
@keyframes loading_circle_animat {
from { transform:rotate(0); }
to { transform:rotate(360deg); }
}
</style>
<!-- 加载动画的 HTML 结构 -->
<div class="loading_container">
<svg class="loading_icon" viewBox="0 0 50 50" version="1.1" xmlns="http://www.w3.org/2000/svg">
<!-- 外圈 -->
<circle stroke="#02bcfe" cx="25" cy="25" r="20" fill="transparent" stroke-width="3" stroke-dasharray="31.415, 31.415" stroke-linecap="round">
<animate attribute-name="animate" values="#3be6cb;#02bcfe;#3be6cb" dur="3s" repeat-count="indefinite" />
</circle>
<!-- 内圈 -->
<circle stroke="#3be6cb" cx="25" cy="25" r="10" fill="transparent" stroke-width="3" stroke-dasharray="15.7, 15.7" stroke-linecap="round">
<animate attribute-name="animate" values="#3be6cb;#02bcfe;#3be6cb" dur="3s" repeat-count="indefinite" />
</circle>
</svg>
<!-- 加载消息插槽 -->
<div class="loading_msg"><slot>加载中...</slot></div>
</div>
`;
}
}
// 导出 WtfLoading 类,支持默认导出和命名导出
export {
WtfLoading,
WtfLoading as default
}