2012-11-05 172 views
3

目前我的div使用兩個按鈕(向上和向下)滾動,但我希望它跳轉到頂部並跳轉到底部,而這兩個按鈕帶有垂直自動滾動(向下)。我如何在jQuery中完成此操作?這是我的代碼到目前爲止:http://jsfiddle.net/NkY8J/垂直滾動div文本

HTML

<div id="scroll"> 
     Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here<br /><br /> 
    Content here and more content here 
     </div> 
       <input id="scroll-up" class="btn" type="button" value="Up"/> 
       <input id="scroll-down" class="btn" type="button" value="Down"/> 
​ 

JS

$(function() { 
    var ele = $('#scroll'); 
    var speed = 25, scroll = 5, scrolling; 

    $('#scroll-up').mouseenter(function() { 
     // Scroll the element up 
     scrolling = window.setInterval(function() { 
      ele.scrollTop(ele.scrollTop() - scroll); 
     }, speed); 
    }); 

    $('#scroll-down').mouseenter(function() { 
     // Scroll the element down 
     scrolling = window.setInterval(function() { 
      ele.scrollTop(ele.scrollTop() + scroll); 
     }, speed); 
    }); 

    $('#scroll-up, #scroll-down').bind({ 
     click: function(e) { 
      // Prevent the default click action 
      e.preventDefault(); 
     }, 
     mouseleave: function() { 
      if (scrolling) { 
       window.clearInterval(scrolling); 
       scrolling = false; 
      } 
     } 
    }); 
}); 
​ 

CSS

#scroll { 
    width: 200px; 
    height: 100px; 
    overflow: hidden; 
    padding: 4px; 
}​ 
+0

「跳到頂部並跳到底部」是什麼意思? –

+0

@Derek如跳轉到div的第一行/跳轉到div的最後一行 – methuselah

回答

1

讓我們來看看這裏。 http://jsfiddle.net/NkY8J/2/

只需設置ele.scrollTop(0);即可跳到頂部。

並設置ele.scrollTop(Math.pow(10,9));跳到底部。

+1

或'ele.scrollTop(Math.pow(10,9));' –

+0

感謝您的回覆!垂直自動滾動怎麼樣?我如何得到這個工作? – methuselah

+1

@methuselah對不起,但我不明白'自動滾動'。將鼠標光標放在按鈕上時,這是自動滾動。 – OammieR