iOS Safari onscroll event within nested element

2020-07-13 07:44发布

My ultimate aim is to have an inline div on my page which horizontally scrolls natively (using -webkit-overflow-scrolling: touch) that also snaps.

I can achieve this without -webkit-overflow-scrolling because I have access to the ontouchend event, so I can calculate my snap when that happens, however, to achieve the best possible UX for this feature, I want to use native-like scrolling on this element.

The problem with using -webkit-overflow-scrolling is that using a flick/some force, the div will continue to scroll for a bit after you've taken your finger off (i.e. AFTER ontouchend has fired); which means my snap calculates before the scrolling is finished.

Having spent a long time trying to find ways round, I have had no success yet.

In the entire page context, safari fires the onscroll event when a scroll is finished. My question is, is it possible to have this event fire within the context of an element? i.e. have onscroll fire inside <div id="slideShow">?

If not, is it possible to either

(a) Access velocity of a ontouchmove for example, so I could calculate when to run the snap?

or

(b) Emulate -webkit-overflow-scroll: touch (the elasticity and velocity effects).

NOTE: For the sake of example, using iPad w/ iOS5.

1条回答
放荡不羁爱自由
2楼-- · 2020-07-13 08:20

The scroll event gets fired on every scrolling container separately, and on iOS only after scrolling has stopped and is complete. You can simply listen for the scroll event on your container.

Here is an example:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>Test Touch Scrolling</title>
        <style>
            body {
                font-size: 15em;
            }
            #outer {
                height: 1200px;
                width: 300px;
                overflow-x: scroll;
                -webkit-overflow-scrolling: touch;
            }
            #inner {
                width: 600px;
            }
        </style>
        <script>
            document.addEventListener("DOMContentLoaded", function() {
                var list = document.getElementById("outer");
                list.addEventListener("scroll", function(event) {
                    alert("Scroll has ended for element with ID '" + event.currentTarget.id + "'");
                });             
            }, false);
        </script>
    </head>
    <body>
        <div id="outer">
            <div id="inner">Some text. And more.</div>
        </div>
    </body>
</html>

You will see the alert only when you have scrolled the text horizontally, not when the out div has been scrolled.

查看更多
登录 后发表回答