2013-01-17 44 views
0

我目前有一個<div>,當頁面向上或向下移動時,它保持位於頁面左側頂部的位置。這工作正常,但不是很順利。將css位置轉換成jquery平滑滑動

我在重新考慮以下代碼,使其成爲平滑滾動條。目前,當觸發發生時,它只是設置CSS top屬性 - 這使得它「緊張」。我有點不確定如何讓反對的CSS頂部值

 //scrolling menu 
    if($("#selectedOptions").length > 0){ //if the element exists 
     $(window).scroll(function(){ 
      var div = $("#selectedOptions");  // the div that slides 
      if(div) {        
       var pos = div.parent().position().top; //position of the top of the wrapper 
       var windowPos = $(window).scrollTop(); //current window postion 

       //top of moving div not to go further than 
       var bottom = $("#sizeAndQuantHeader").position().top; //where the div shouldn't go past 

       //de-bug 
       //console.log("pos: " + pos + " - winpos" + windowPos + ", heih: " + divHieght + " doc he: " + $(document).height() + " bott" + bottom); 

       //if between the range then display at new postion 
       if (windowPos > pos && (windowPos < bottom)) { 
        div.css("top", windowPos-pos); 
        //must be higher than its current position so set to 0 
       } else if (windowPos < pos && windowPos < bottom) { 
        div.css("top", 0); 
       } 
      } 
     }); 
    } 

任何幫助或如何使一個<div>滾動提示設置到其確切位置這是一個平滑滾動運動平穩下來的網頁會更讚賞。

**更新

不幸的是,我有一個已經滾動瀏覽不同的頁面區域元素:

var _scrollTo = function(div){ 
    $('html,body').animate({ 
     scrollTop: div.offset().top}, 
     'slow'); 
}; 

現在,當上面的函數被調用,我認爲它會觸發電話:

$(window).scroll(function(){animate div... 

並延遲新動畫div的滾動。我不能使用回撥,因爲它在其他地方被重新使用。我可能會在這裏錯過一些東西,所以我已經回到沒有動畫。

回答

1

的關鍵就在這裏更改此代碼:

if (windowPos > pos && (windowPos < bottom)) { 
    div.css("top", windowPos-pos); 
    //must be higher than its current position so set to 0 
} else if (windowPos < pos && windowPos < bottom) { 
    div.css("top", 0); 
} 

if (windowPos > pos && (windowPos < bottom)) { 
    div.animate({top: windowPos-pos}, 100); 
    //must be higher than its current position so set to 0 
} else if (windowPos < pos && windowPos < bottom) { 
    div.animate({top: "0"}, 100); 
} 

jQuery's animate()是很容易使用/操作。

+0

這樣做的伎倆,非常感謝你! – Dezza

+0

@dezza很高興爲您提供幫助(: – George

+0

)我不能詆譭原始答案,但要小心整頁動畫不利於此動畫。請參閱**更新 – Dezza

2

使用Animate使其平滑。

div.animate({ top: windowPos-pos }, 300); 
0

新增CSS以DIV(#selectedOptions)

transition: all 0.5s ease 0s; 
-moz-transition: all 0.5s ease 0s; 
-webkit-transition: all 0.5s ease 0s; 
-o-transition: all 0.5s ease 0s; 

它會自動去平滑。