How to center image in the specific div according to current viewport position?

前端 未结 5 2091
时光说笑
时光说笑 2021-02-14 20:37

I am trying create nice animation during loading content using ajax. I want to use display icon during reloading div with \"Content\", however I can\'t figured out is it possibl

5条回答
  •  闹比i
    闹比i (楼主)
    2021-02-14 21:07

    For this to work to your requirements you will need to use JavaScript to determine where the loading image needs to be placed over the visible part using a fixed position div and then reposition it when the user resizes the window or scrolls the window so it is always in the desired position.

    $(window).scroll(function() {
        scrolling();
    });
    
    $(window).resize(function() {
       scrolling(); 
    });
    
    scrolling();
    
    function scrolling() {
        var windowHeight = $(window).height();
        var scrollTop = $(window).scrollTop();
        var offsetTop = $('#thediv')[0].offsetTop;
        var offsetHeight = $('#thediv')[0].offsetHeight;
    
        var offsetWidth = $('#thediv')[0].offsetWidth;
    
        var top = offsetTop - scrollTop;
        top = top < 0 ? 0 : top;
    
        var bottom = (scrollTop + windowHeight) - (offsetHeight + offsetTop);
        bottom = bottom < 0 ? 0 : bottom;
    
        $('.image').css('top', top);
        $('.image').css('bottom', bottom);
        $('.image').css('width', offsetWidth);
    }
    

    Please note that if you change the width of the div you will always need to call the scrolling() function so that it can recalculate the position.

    I also added the loading image as a background image to the fixed div so that we can use CSS to centre it.

    .image {
        position: fixed;
        text-align:center;
        background-image:url('http://i.stack.imgur.com/FhHRx.gif');
        background-repeat:no-repeat;
        background-position:center center;
        background-color:rgba(255,255,255,.4);
    }
    

    Here is the JSFiddle http://jsfiddle.net/QWB9x/89/

提交回复
热议问题