简体   繁体   中英

Fix scroll position in place when setting body to position:fixed (ios)

Ok, so I have a page with a button which activates an overlay using jQuery. In order to prevent the content behind the overlay from scrolling on devices such as iPhone, I am using the following code to toggle the class of 'body' to one which is set to position: fixed, overlay: hidden.

<script>
$(document).ready(function(){
    $("#filter-btn, .close-filter").click(function(){
        $("body").toggleClass("fix");
    });
});
</script>

This works, except for the fact that when the button is clicked to activate the overlay, the page returns to the top which is not what I want - I would like the current scroll position to remain.

I'm guessing I need to use some JS here to get the scroll position and fix it in place, and then disabling that when the overlay is closed. Thing is, I'm not sure how.

Any ideas?

The body would "scroll" to the top because it is being fixed to the top.

Try:

$('html, body').css({'overflow': $('html, body').css('overflow')=='hidden'?'auto':'hidden'});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM