2013-07-12 15 views
0

我有一個問題,請使用Javascript幫助的Javascript:如何提高鼠標滾動到目標片段

  • 我們如何可以讀取滾動事件(鼠標滾動到頂部或向下)?
  • ,如何照顧我們讀到鼠標滾動

的結構是這樣的

<div id="listofstuff"> 
<div class="anitem"> 
    <span class="itemname">Item1</span> 
    <span class="itemdescruption">AboutItem1</span> 
</div> 
<div class="anitem"> 
    <span class="itemname">Item2</span> 
    <span class="itemdescruption">AboutItem2</span> 
</div> 
<div class="anitem"> 
    <span class="itemname">Item3</span> 
    <span class="itemdescruption">AboutItem3</span> 
</div> 
<div class="anitem"> 
    <span class="itemname">Item4</span> 
    <span class="itemdescruption">AboutItem5</span> 
</div> 
<div class="anitem"> 
    <span class="itemname">Item5</span> 
    <span class="itemdescruption">AboutItem5</span> 
</div> 

比方說,用戶首次來到我的網絡來觸發某些事件,它們將向下滾動後看到項目1 ,頁面自動平滑滾動到項目2

現在,當他們在項目中2

  • 如果他們向下滾動 - 它關係到項目3
  • 如果他們向上滾動 - 它可以追溯到第1項

這個網站做我想要達到的目標:http://onlinedepartment.nl/

+1最佳答案:)

回答

1

被盜

$("body").mousewheel(function(event, delta) { 

     this.animate({ 
      scrollTop:theoffset 
     }, 'slow'); 

     event.preventDefault(); 

    }); 

}); 

您需要使用JavaScript來聽取「鼠標滾輪」事件。

然後使用事件e.wheelDelta來確定用戶滾動的方向。

我不得不使用a debounce function I found here來防止事件被多次觸發,導致幻燈片滾動到底部。

var amountOfSlides = 4; 
var counter = 1; //at slide 
var main = document.getElementById('main'); 
var currentPos = 0; 

//The scroll event fires way to many times so we need to use 
//debounce to only get the event once per scroll; 
window.addEventListener('mousewheel', debounce(function(e) { 

    //Check to see if the scroll is going up or down. 
    if(e.wheelDelta >= 0) { 

     //going up so make sure that the user isn't already at the top 
     if(counter <= 1) return; 
     currentPos = currentPos + window.innerHeight; 
     counter--; 

    } else { 

     //going down. make sure the user is not at the bottom. 
     if(counter >= amountOfSlides) return; 
     currentPos = currentPos - window.innerHeight; 
     counter++; 
    } 

    //change the position of the margin so that the slides move. 
    document.getElementById('main').style.marginTop = currentPos + "px"; 

}, 250)); 

// http://remysharp.com/2010/07/21/throttling-function-calls/ 
function debounce(fn, delay) { 
    var timer = null; 
    return function() { 
     var context = this, args = arguments; 
     clearTimeout(timer); 
     timer = setTimeout(function() { 
      fn.apply(context, args); 
     }, delay); 
    }; 
} 

對於幻燈片之間的轉換,我使用了CSS3轉換,因爲它們比JavaScript動畫更流暢。

唯一的問題是當用戶調整窗口大小(需要刷新),但我希望這給你一個好的開始,因爲這個問題可以很容易地排序,因爲幻燈片調整大小爲100%使用CSS的窗口的高度。

html, body, #main{ 
    height:100%; 
    margin:0; 
} 
body { 
    overflow:hidden; 
} 
#main { 
    transition:1s; 
} 
article { 
    height:100%; 
} 

爲了簡單起見,我沒有使用HTML,但您可以輕鬆地自行更改它。

<section id="main"> 
    <article></article> 
    <article></article> 
    <article></article> 
    <article></article> 
</section> 

這裏是一個jsFiddle向你展示它如何工作,希望這有助於。 http://jsfiddle.net/9wrDT/

+0

好的,它的工作 –

+0

我加了正確的鏈接對不起。 – jamcoupe