簡體   English   中英

以編程方式使div元素在另一個div元素內垂直滾動

[英]Making a div element programmatically and vertically scroll within another div element

我想展示一種適合移動設備的布局。 為此,我要在其中放置一個裝有大iPhone的頁面。 在屏幕區域中,我希望我的布局出現並自動垂直向下滾動,然后向上滾動到初始點。

我為此找到了一個垂直旋轉木馬 ,但我希望它是自動的。 有沒有簡單的方法可以做到這一點?

由於您沒有提供代碼,因此我制作了自己的原型。 調整此代碼以滿足您的需求,如果您添加代碼,我可以為您完成。 這是基本思想。

<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>

如果您希望它在完成后重新出現,只需在最后添加page.scrollTop = 0 如果要再次運行它,請將times設置為0,然后將其放入函數中,然后在clearInterval();之后再次運行該間隔clearInterval();

希望我能幫上忙! 如果有什么您不清楚,只是在下面發表評論。

完成一: jsFiddle

盡可能簡單(僅出於記錄目的進行編輯):

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 在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM