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})

效果如下: