Prevent background image from resize on scrolling

后端 未结 2 1454
挽巷
挽巷 2021-01-20 11:49

I have background image that is resizing a little bit when I scroll from the top on mobile devices. And it returns to its size when I scroll to the top agai

2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-20 12:25

    If the background-image is resizing on initial scroll, I assume the element with that background must have a dynamic height, generated using either vw/vh in the CSS or JS/jQ script. I ran into this same problem, and I found what I believe to be the correct method in resolving this issue (at least until mobile browsers provide their own workaround).

    Using a simple jQuery function, you can store the window's width on page load, and use that to restrict the container's resizing function to viewport sizes wider than the desktop breakpoint (992px+) and narrower viewports so long as the viewport width changes, not just the height. This way, on mobile and tablet devices, when you scroll, there is only a vertical viewport resize, so the resize function is not triggered.

    var breakpoint = 991;
    var bgHeight = function() {
        $('#bg').css('height', $(window).height() + 'px');
    }; bgHeight();
    var windowWidth = $(window).height();
    $(window).on('resize', function() {
        if ((($(this).width() <= breakpoint) && ($(this).width() != windowWidth))
            || ($(this).width() > breakpoint)) {
            bgHeight();
        }
        windowWidth = $(window).width();
    });
    

    CodePen: https://codepen.io/brandonmcconnell/pen/jayYbB

提交回复
热议问题