Prevent Body Element From Scrolling On Touch Devic

2019-06-09 08:38发布

问题:

The Problem:

I have a web application on the iOS homescreen so there is no browser window and it looks and functions very well. I've figured out how to make inner div elements do the touch scrolling events and use the momentum/bounce style in iOS, and that works perfectly... the issue I run into now is that the bounce scrolling (again, iOS-only) is messing up any fixed elements or site-related animations I have on the page.

When I try the following:

document.ontouchmove = function(e) {e.preventDefault()};

The issue stops, but now I can't scroll anywhere on my application.

What I Need:

I want the body to be completely locked in place... If someone grabs, say, my sidebar or navbar and then pulls on the page, the body bounces! But if someone is inside the content area, there is no issue at all--the application scrolls flawlessly and looks great. If I stop scrolling on the sidebar or navbar or body, all scrolling in the application will not working and is essentially nonfunctional.

tl;dr: Body bounces on scroll. I want a scrolling content area and no scroll anywhere else. The body should NEVER move, but elements I deem scrollable within the body should.

As a sidenote, I've browser the following popular questions/solutions posted (among many others):

1 2 3

I just wanted to post that up before people assumed I didn't do any searching... I've been at this for hours now and have seen even more solutions than posted above, but I wanted to get the most popular ones listed above so no one thought this was a duplicate question.

回答1:

I figured this out a few days ago and have this handy jsbin set up to demonstrate what I did to make this work:

My Working jsbin Example

When you open this link on an iPad, the text should be scrollable. Try tugging around the rest of the screen when there is no current touchmove event currently working.

If you play around with it, you'll notice that only the inner textfield moves as expected. This is determined by putting my .scrollable class within the .container class. The .scrollable class takes up the full height of it's parent container.

Now make the container a larger height, like height: 500px. The goal here is to make it large enough to have no overflow yet small enough to have other whitespace on the iPad still. Try scrolling it or pulling it... No touchmove events are fired and the screen stays in place.

My JS determines if an object has overflow after being touched. If it does, it scrolls. If it does not, it does not send a scroll event.

Play with it and let me know if I can provide any better examples and also if you run into any bugs... Right now the only one I know of is if you're really trying to break it and start tugging around the site while a current touchmove event is being fired, or the page is first loading... I wouldn't count those as "bugs", but if you can find a fix for those too, I'm all ears!