layui 让弹窗始终居中于屏幕

前话:今天用 layer.confirm()  弹窗的时候,滚动到页面尾部再弹窗时,发现弹窗还显示在上面,要滚动会上面才能看到。

度娘找了一个获取滚动条位置的方法:

    function ScollPostion() { //滚动条位置
        var t, l, w, h;
        if(document.documentElement && document.documentElement.scrollTop) {
            t = document.documentElement.scrollTop;
            l = document.documentElement.scrollLeft;
            w = document.documentElement.scrollWidth;
            h = document.documentElement.scrollHeight;
        } else if(document.body) {
            t = document.body.scrollTop;
            l = document.body.scrollLeft;
            w = document.body.scrollWidth;
            h = document.body.scrollHeight;
        }
        return {
            top: t,
            left: l,
            width: w,
            height: h
        };
    }

要让弹窗显示在当前滚动位置中间才对,

所以,我拿的是 当前滚动条的高度 + 当前可见区域大小的一半高度 ,(这是我粗略算的,更精确定位中间还可以优化)

// 滚动条当前中间位置距离顶部高度
var y = ScollPostion().top + $(window).height()/2;

// 用弹窗参数 offset 坐标
layer.confirm('弹窗?', {offset:y})

效果如下: