2010-04-09 37 views
6

目的如何使用jQuery在DIV內連續滾動內容?

目的是一個具有固定的高度和寬度具有容器DIV和具有內的HTML內容垂直連續DIV自動滾動顯示。

問題 基本上我已經創建下面使用jQuery滾動(移動)子DIV垂直向上的代碼,直到它的邊界框父其中動畫隨後完成其觸發的事件處理程序,其重置的位置外孩子DIV並再次啓動該過程。

這工作正常,所以內容向上滾動留下一個空白區域,然後再次從底部開始滾動。

我遇到的問題是,對於內容的要求就好像它不斷重複出現,請參見下圖以更好地解釋這一點,有沒有辦法做到這一點? (我不希望使用第三方插件或庫比jQuery的除外):

alt text http://www.cameroncooke.com/playground/scrolling-example.gif

我有什麼到目前爲止

的HTML:

<div id="scrollingContainer"> 

    <div class="scroller"> 

    <h1>This is a title</h1> 

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse at orci mi, id gravida tellus. Integer malesuada ante sit amet enim pulvinar congue. Donec pulvinar dolor et arcu posuere feugiat id et felis.</p> 

    <p>More content....</p> 

    </div> 

</div> 

該CSS:

#scrollingContainer{ 
    height: 300px; 
    width: 300px; 
    overflow: hidden; 
} 

#scrollingContainer DIV.scroller{ 
    position: relative; 
} 

中的JavaScript:

/** 
* Scrolls the content DIV 
*/ 
function scroll() { 

    if($('DIV.scroller').height() > $('#scrollingContainer').height()) { 

    var t = $('DIV.scroller').position().top + $('DIV.scroller').height(); 

    /* Animate */ 
    $('DIV.scroller').animate(
    { 
     top: '-=' + t + 'px' 
    } 
    , 4000, 'linear', animationComplete); 
    } 
} 

function animationComplete() { 
    $(this).css('top', $('#scrollingContainer').height()); 
    scroll(); 
} 

回答

3

你需要複製你的內容元素,並對準他們,使他們上下彼此相鄰,並串聯滾動它們。您當前的滾動應該可以工作,跳躍將不可見,因爲它應該從底部元素的頂部跳到頂部元素的頂部,也就是說,跳轉到相同的部分。我把這兩個內容副本(你可以只是.clone它得到另一個副本)在一個容器中滾動,這樣你就不必擔心移動兩個元素。

如果您想真正優化它,您只能在底部元素中顯示內容的頂部(足以隱藏跳轉),但除非您的內容非常複雜和繁重,否則不值得付出努力。

1

你想讓內容「自動重複」並永遠滾動嗎?您應該能夠在文本下方添加新的DIV,並將該文本複製到新的DIV中。根據滾動位置執行此操作,當它從視圖中移出時移除上面的DIV。基本上,你只是複製文本,將新的DIV推到「堆棧」的底部,並在不可見時將其彈出頂端。

0

簡單地說,你需要兩個大於滾動框的div,並且你需要移動一個不可見的標記。如果兩者完全相同,則不應引起注意。

0

試試這個:

$('.upBut').bind('click',function(){ 
    $('.articleWrapper').prepend($('.article:last')).children('.article:first').css({display:'none'}).show('slow'); 
}); 
$('.downBut').bind('click',function(){ 
    //$('.articleWrapper').append($('.article:first')).children('.article:last').css({display:'none'}).show('slow'); 
    $('.article:first').hide('slow',function(){$(this).appendTo('.articleWrapper').show('slow');}); 
}); 
$('.upBut').hover(function(){$(this).css("background-image", "url(images/up_green.png)");},function(){$(this).css("background-image", "url(images/up_red.png)");}); 
$('.downBut').hover(function(){$(this).css("background-image", "url(images/down_green.png)");},function(){$(this).css("background-image", "url(images/down_red.png)");}); 

工作例子可以看這裏: http://www.timeswellness.com/index.aspx?page=others&rightnav=false&do=CancerDay