简体   繁体   中英

Javascript prevent scrolling if a scrollable div is overflowing

I'm working on a ios web app, it has a header and tab bar and in the center there is a scrollable div. It feels like a native ios app if the div is overflowing which means there is enough content to make it scroll. But when there isnt enough content when you try and scroll the div the entire page is flicked up. So anyway what I want to do is prevent scrolling on the entire page if the div can't scroll.

You can use this to prevent scrolling on the page.

document.body.addEventListener('touchmove', function(e){ e.preventDefault(); });

I'm wondering if anyone can help me out and tell me how to detect if a div is overflowing.

Just to make sure, The div you are using, did you set the css code of overflow-y: scroll; ? You could fix this if you changed it to overflow-y: auto; in that case.

Check during touchstart if the height of the content is >= the height of the container. If it is, then disable scrolling on the element.

$(".container").on("touchstart", function(e){
    var childHeight $(".child-element-container"). outerHeight();
    var containerHeight = $(".container"). outerHeight();
    if (childHeight <= containerHeight){
        $(".container").on("touchmove", false);
    } else {
        $(".container").off("touchmove");
    }
}

Obviously you'll need to change some things around, and you can modify it to disable scrolling on the entire page. If you have custom events for scrolling when it should be scrolling, you'll need to add the event after turning it .off .

Another solution, which is more complicated but doesn't require turning on/off events would be to add a dummy div to the container that accounts for the content + unused space + 2px , then run a timer to see if it's near the top of bottom of the container, then use scrollTop(1) or scrollTop(childHeight - 1) so that it situates the content always 1px from the limit, consequently disallowing the entire page drag.

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