Find element that's on the middle of the visible screen (viewport), on scroll

前端 未结 3 2027
太阳男子
太阳男子 2021-01-02 10:48

I need to know if there is a way I can determine if a div is in the center of the screen.

HTML:

3条回答
  •  余生分开走
    2021-01-02 11:44

    The height of the window and the scrollTop() of the window will give you the range of offsets that exist in the users view:

    var minHeight = $(window).scrollTop()
    var maxHeight = $(window).height()
    var middleHeight = (maxHeight + minHeight) / 2;
    

    You could try using a viewport selector such as: http://www.appelsiini.net/projects/viewport This will give you all visible elements. A plugin isn't needed but will ease the selection

    var visibleElements = $("div.box").filter(":in-viewport")
    

    From this selection you can then look for the element closest to the middleHeight:

    var $midElement;
    var distance = null;
    var currDistance = 0;
    visibleElements.each(function(index, element) {
        currDistance = Math.abs(middleHeight - $midElement.offset().top);
        if ( distance == null || currDistance < distance ) {
            $midElement = $(element);
            distance = currDistance;
        }
    });
    

    Haven't tested this but it should be along the right track.

提交回复
热议问题