美文网首页
js获取屏幕可见区域高度

js获取屏幕可见区域高度

作者: 丶灰太狼他叔 | 来源:发表于2018-10-08 11:19 被阅读10次

    需求是做一个购物车底部结算栏不在可见区域时固定底部,类似淘宝。代码:

    /**
     * 购物车结算栏底部固定
     */
    function totalFixed() {
        // 默认未定位
        $('.goods-total').css({ 'position': 'static' });
        var box = $('.goods-total'), st;
        var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
        box.attr('offTop', h - box.offset().top - box.height());
        if (parseInt(box.attr('offTop')) < 0) {
            box.css({ 'position': 'fixed', bottom: 0 });
        }
        $(window).scroll(function () {
            st = Math.max(document.body.scrollTop || document.documentElement.scrollTop);
            if (parseInt(box.attr('offTop')) < 0) {
                if (st > Math.abs(parseInt(box.attr('offTop')))) {
                    box.css({ 'position': 'static' });
                } else {
                    box.css({ 'position': 'fixed', bottom: 0 });
                }
            }
        });
    }
    $(function () {
        totalFixed();
    });
    
    /**
     * 浏览器窗口发生变化时,重新计算结算栏位置
     * @param ev
     */
    window.onresize = function (ev) {
        totalFixed();
    }
    

    基本逻辑如代码,关键在于获取屏幕可见高度的兼容性document.documentElement.clientHeight之前是这样获取的,PC端没什么问题,就是手机浏览器打开时,出现异常。网上查了下,最终的实现代码

    var w=windows.innerWidth
    || document.documentElement.clientWidth || document.body.clientWidth; var h=window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    
    

    相关文章

      网友评论

          本文标题:js获取屏幕可见区域高度

          本文链接:https://www.haomeiwen.com/subject/syvdaftx.html