简体   繁体   中英

Making a div element programmatically and vertically scroll within another div element

I want to showcase a mobile-friendly layout. To do that, I have a page with a big iPhone in it. In the screen area, I want my layout to appear and automatically scroll down vertically then scroll up to initial point.

I found a vertical carousel for that, but I'd like it to be automatic. Is there a simple way to achieve that?

As you didn't give the code, I made my own prototype. Tweak this code to fit your needs, if you add code I can do it for you. Here is the basic idea.

<body style="background: grey;">
    <div style="width: 400px; height: 800px; background: white; overflow-y: hidden;" id="page">
        <div style="height: 2000px; width: 385px;">
            <div style="background: red; height: 400px; width: 400px;"></div>
            <div style="background: blue; height: 400px; width: 400px;"></div>
            <div style="background: green; height: 400px; width: 400px;"></div>
            <div style="background: yellow; height: 400px; width: 400px;"></div>
            <div style="background: purple; height: 400px; width: 400px;"></div>
        </div>
    </div>
    <script>
        var page = document.getElementById('page');
        var times = 0;
        window.setInterval(function(){
            times++;
            page.scrollTop = times;
            if(times == 1200){
                window.clearInterval();
            }
        }, 5);
    </script>
</body>

If you want it to come back up after completing just add page.scrollTop = 0 at the end. If you want to run it again set times to 0 and run that interval again by putting it into a function, right after clearInterval(); .

I hope I helped! If there's something you're not clear about just comment below.

Finished one: jsFiddle

As simple as it can get (edited just for the record):

HTML :

<div id="Outer">
    <div id="Inner">
       …
    </div>
</div>

CSS :

#Outer {
    width: 300px;
    height: 400px;
    background: red;
    overflow-y: scroll;
}

#Inner {
    margin: 16px 16px;
    background: yellow;
}

Javascript :

step = 0;

int_1 = setInterval( function() {
    step++;
    Outer.scrollTop = step;
    if (step >= Outer.offsetHeight+16) {
        clearInterval(int_1);
        setTimeout( function() {
            int_2 = setInterval( function() {
                step--;
                Outer.scrollTop = step;
                if (step <= 0) {
                    clearInterval(int_2);
                }
            }, 5);
        }, 500);
    }
}, 5);

JSFiddle here .

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