2012-12-07 42 views
1

我有一個基本上是四個div的網站 - 每個網站都設置爲窗口的高度,這樣整個文檔就是窗口高度的四倍。如何「捕捉」滾動到最近的預定義位置?

的想法是,在一個div上點擊一個「窗口高度」推進滾動 - 這工作得很好,像這樣:

// on click event 

if(cur_frame<number_slides){ 
    scrolling = true; 
    $('html,body').animate({scrollTop:window_height*cur_frame},function(){ 
     scrolling=false; 
    }); 
} 

用戶滾動後的頁面手動然而,我喜歡將位置「捕捉」到窗口高度的最接近的倍數 - 因此給定的div再次集中在屏幕上。我嘗試使用超時,盤算,一個小的延遲將保持它觸發一千倍第二...

// on scroll event 

clearTimeout(scroll_timer); 
if(!scrolling) scroll_timer = setTimeout(function(){ 
    if(cur_scroll!=window_height*(cur_frame-1)) { 
     scrolling = true; 
     $('html,body').stop().animate({scrollTop:window_height*(cur_frame-1)},function(){ 
     scrolling = false; 
     }); 
    } 
},100); //20? 400? 1000? 

...但不能攻擊腳本爭奪滾動位置的用戶之間的平衡,或者是一個嚴重的延遲,從而破壞了「捕捉」效應。

任何建議如何實現?

回答

-1

您可以使用javascript來做到這一點,也可以使用稍微簡單一些的舊解決方案,您可以使用頁面錨點。 如果您將document.location.hash更改爲頁面中存在的錨點,則瀏覽器將滾動到該錨點。 所以在你的HTML把一些錨頁面:

<a name="anchor1" id="anchor1"></a> 

然後在您的JS放:

document.location.hash = "anchor1"; 
+1

一個問題......真的沒有「滾動」的頁面錨。 – Sparky

+0

是的,我知道在哪裏滾動 - 這個問題是一個平滑的'捕捉'效果。 –

+1

頁面錨點的全部點是捕捉到一個位置!它確實起作用,我在FF Chrome和IE上試了一下,然後才發佈了答案。不能相信我被拒絕了! –

4

jQuery的scrollsnap此插件支持到IE9。

你在找什麼叫做「Scroll Snap」。

<script src="demo/foundation/javascripts/jquery.js"></script> 
<script src="src/jquery.event.special.js"></script> 
<script src="src/jquery.easing.min.js"></script> 
<script src="src/jquery.scrollsnap.js"></script> 
<script type="text/javascript"> 
$(document).ready(function() { 
    $(document).scrollsnap({ 
     snaps: '.snap', 
     proximity: 50 
    }); 
}); 
</script> 
0

如果你要考慮一個跨瀏覽器的JavaScript重新實現本地CSS 滾動捕捉 SP的EC,因爲已經回答了這裏:How to emulate CSS Scroll Snap Points in Chrome?,你可以使用 this library

主要理由使用,而不是本機的CSS解決方案,它適用於所有現代瀏覽器,並有一個可定製配置,以允許自定義定時在轉換和滾動檢測。

庫重新實現的CSS卡扣特徵使用香草的javascript緩和功能,並適用於使用的容器元素的scrollTop/scrollLeft屬性的值和所述滾動事件監聽器

這裏是示出了如何一個例子使用它:

import ScrollSnap from 'scroll-snap' 

const snapConfig = { 
    scrollSnapDestination: '90% 0%', // scroll-snap-destination css property, as defined here: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-snap-destination 
    scrollTimeout: 100, // time in ms after which scrolling is considered finished 
    scrollTime: 300 // time in ms for the smooth snap 
} 

function callback() { 
    console.log('called when snap animation ends') 
} 

const element = document.getElementById('container') 
const snapObject = new ScrollSnap(element, snapConfig) 

snapObject.bind(callback) 

// unbind the element 
// snapObject.unbind(); 
+0

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的基本部分,並提供參考鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 - [來自評論](/ review/low-quality-posts/18771242) –