• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

模态对话框

开发技术 开发技术 6小时前 2次浏览

接口

interface IModal {
    root: HTMLElement;
    container: HTMLElement;
    content: HTMLElement;

    mount(root?: HTMLElement): IModal;
    appendContent(content: HTMLElement): IModal;
    remove(): IModal;
}

code

/**
 * 计算el元素及其子元素的z-index最大值
 */
function calcZIndex(el: HTMLElement = document.body): number {
    var max = el['computedStyleMap'] ?
        el['computedStyleMap']().get('z-index').unit === 'number' ? Number.parseInt(el['computedStyleMap']().get('z-index').value) : 0
        :
        el.style.zIndex === '' ? 0 : Number.parseInt(el.style.zIndex);
    Array.from(el.children).forEach(it => {
        var childZIndex = calcZIndex(it as HTMLElement);
        if (childZIndex > max) {
            max = childZIndex;
        }
    })
    return max;
}

function setStyles(el: HTMLElement, styles: React.CSSProperties) {
    for (let key in styles) {
        el.style[key] = styles[key];
    }
}

class Modal implements IModal {
    root: HTMLElement;
    container: HTMLElement;
    content: HTMLElement;

    constructor() {
        var container = document.createElement('div');
        this.container = container;
        setStyles(container, {
            position: 'absolute',
            top: 0,
            left: 0,
            width: '100%',
            height: '100%',
            background: 'transparent',
        });
        this.createContent();
    }
    private createContent() {
        var content = document.createElement('div');
        this.content = content;
        setStyles(content, {
            position: 'absolute',
            minWidth: '180px',
            minHeight: '100px',
            top: '50%',
            left: '50%',
            transform: 'translate(-50%, -50%)',
            background: 'rgba(255, 255, 255, 0.6)',
        });
        this.container.appendChild(content);
    }
    appendContent(content: HTMLElement): IModal {
        this.content.appendChild(content);
        return this;
    }
    mount(root: HTMLElement = document.body): IModal {
        root.appendChild(this.container);
        this.root = root;
        setStyles(this.container, {
            zIndex: calcZIndex(root) + 1,
        });
        return this;
    }
    remove(): IModal {
        this.root.removeChild(this.container);
        return this;
    }
}

export default Modal;

END


程序员灯塔
转载请注明原文链接:模态对话框
喜欢 (0)