Using jquery to get element's position relative to viewport

前端 未结 6 1238
囚心锁ツ
囚心锁ツ 2020-12-07 08:09

What\'s the proper way to get the position of an element on the page relative to the viewport (rather than the document). jQuery.offset function seemed promising:

6条回答
  •  一生所求
    2020-12-07 08:39

    Here is a function that calculates the current position of an element within the viewport:

    /**
     * Calculates the position of a given element within the viewport
     *
     * @param {string} obj jQuery object of the dom element to be monitored
     * @return {array} An array containing both X and Y positions as a number
     * ranging from 0 (under/right of viewport) to 1 (above/left of viewport)
     */
    function visibility(obj) {
        var winw = jQuery(window).width(), winh = jQuery(window).height(),
            elw = obj.width(), elh = obj.height(),
            o = obj[0].getBoundingClientRect(),
            x1 = o.left - winw, x2 = o.left + elw,
            y1 = o.top - winh, y2 = o.top + elh;
    
        return [
            Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),
            Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))
        ];
    }
    

    The return values are calculated like this:

    Usage:

    visibility($('#example'));  // returns [0.3742887830933581, 0.6103752759381899]
    

    Demo:

    function visibility(obj) {var winw = jQuery(window).width(),winh = jQuery(window).height(),elw = obj.width(),
        elh = obj.height(), o = obj[0].getBoundingClientRect(),x1 = o.left - winw, x2 = o.left + elw, y1 = o.top - winh, y2 = o.top + elh; return [Math.max(0, Math.min((0 - x1) / (x2 - x1), 1)),Math.max(0, Math.min((0 - y1) / (y2 - y1), 1))];
    }
    setInterval(function() {
      res = visibility($('#block'));
      $('#x').text(Math.round(res[0] * 100) + '%');
      $('#y').text(Math.round(res[1] * 100) + '%');
    }, 100);
    #block { width: 100px; height: 100px; border: 1px solid red; background: yellow; top: 50%; left: 50%; position: relative;
    } #container { background: #EFF0F1; height: 950px; width: 1800px; margin-top: -40%; margin-left: -40%; overflow: scroll; position: relative;
    } #res { position: fixed; top: 0; z-index: 2; font-family: Verdana; background: #c0c0c0; line-height: .1em; padding: 0 .5em; font-size: 12px;
    }
    
    

    X:

    Y:

提交回复
热议问题