Prevent background image from resize on scrolling

后端 未结 2 1453
挽巷
挽巷 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

    0 讨论(0)
  • 2021-01-20 12:32

    Take a look at background: fixed no repeat not working on mobile.

    I believe the main difference is the z-index=0, try changing it to -10.

    0 讨论(0)
提交回复
热议问题