2012-06-20 48 views
1

我試圖建立誰跟隨用戶滾動右邊框:格遵循滾動

CSS:

 .clearfix:after { 
      content: " "; 
      display: block; 
      font-size: 0; 
      height: 0; 
      clear: both; 
      visibility: hidden; 
     } 

     .wrapper { 
      border: 1px solid black; 
     } 

     .column { 
      float: left; 
      border: 1px solid red; 
     } 

     .relative { 
      position: relative; 
      margin-top: 0px; 
     } 

HTML:

<div class="wrapper clearfix"> 
    <div class="column"> 
     small or big text 
    </div> 
    <div class="column"> 
     <div class="dmap relative">a</div> 
     <span>some other crazy stuff</span> 
    </div> 
</div> 

的Javascript :

referencey = $(".dmap").offset().top; 

$(window).scroll(function (event) { 

    var y = $(this).scrollTop(); 

    if (y >= referencey) { 
     $(".dmap").css("margin-top", y - referencey) 
    } else { 
     $(".dmap").css("margin-top", 0); 
    } 

}); 

該代碼工作得很好。列大小是不相關的,因爲我所做的只是更改margin-top,這意味着列和包裝器總是獲得新的大小。代碼的缺點是在用戶滾動時小小的跳躍。

避免滾動時的小跳轉的替代方法不是更改邊距頂部,而是在y >= referencey之後將框的位置更改爲固定。解決方案的缺點是相對於列大小而言是一個非常棘手的行爲,因爲當我將類更改爲fixed時,它不再佔用右列中的空間,如果左列較小,則會出現一整套新bug 。

+0

最好將盒子放在絕對位置。 – undefined

+1

你試過了'position:fixed;'? – Andy

+0

@undefined如果您在包裝盒中使用固定的位置,它會運行更多冰沙,但由於固定的採購,包裝不再適合包裝盒。 = \ – user1330271

回答

1

我想出了一個解決方案,不解決問題,但解決它。我所做的是在用戶停止滾動後滾動框。不同的效果,但不小的跳躍(它也看起來很酷)。

var scrolly = $(".dmap").offset().top; 
var scroll = false; 

$(window).scroll(function (event) { 

    var y = $(this).scrollTop(); 

    if (scroll) { 
     clearTimeout(scroll); 
    } 

    scroll = setTimeout(function() { 
     $(".dmap").animate(
      { marginTop: (y >= scrolly ? y - scrolly : 0) }, 
      { queue: false, duration: 200 } 
     ); 
    }, 100); 

}); 
0

它是一條簡單的線條; position: fixed; 這意味着該對象固定在頁面上,以便在滾動時遵循該頁面。

+0

就像我說過的:避免滾動時的小跳轉的另一種方法是不要更改邊距頂部,但是在y> = referencey後將框的位置更改爲固定。該解決方案的缺點是相對於列大小的錯誤行爲。 – user1330271