使用jquery寫一個熱鍵(J/K)動態滾動瀏覽外掛程式

來源:互聯網
上載者:User

加班之餘很無聊,幾分鐘足夠寫個彩蛋夾在裡面自娛自樂。。。

實現的效果很簡單,用j/k鍵自動翻滾上一條/下一條動態資訊,和twitter、微博、g+等等一樣,乃懶人IB利器。

主要解決的問題就是判斷當前顯示在第幾條之上,如此獲得動態列表中一條的索引位置,從而得到之前或之後對應的scrollTop值。為此需要遍曆當前動態列表的每個元素,對其和當前的視窗scrollTop值作對比,把剛好不大於該值的那條索引作為參考物來進行之後的計算。www.2cto.com

基本的代碼如下:

01
var eventNS='keydown.timelineHotkeys';
02
$(document).unbind(eventNS).bind(eventNS,function(e){
03
    //wrapobj為動態列表外的包裹對象
04
    var wrapobj=$('.timeline-feeds:visible').eq(0);
05
    if(wrapobj.length>0){
06
        var code = e.keyCode;
07
        //feedItemList為每個動態列表對象
08
        var feedItemList=wrapobj.find('.item');
09
        if(code===74||code===75){   
10
            var scrollTop=$(window).scrollTop();
11
            //這裡的60像素是頁面頂部到第一條動態之間的間隔距離
12
            var feed2TopPx=60;                          
13
            scrollTop+=feed2TopPx;
14
            var curViewIndex=-1;
15
            var curOfst=0;
16
            feedItemList.each(function(i){
17
                var ofst=$(this).offset().top;
18
                if(ofst<scrollTop){
19
                    curViewIndex=i;
20
                    curOfst=ofst;
21
                }
22
            });
23
            if(code === 74) { // 按下j鍵時的處理(down)
24
                curViewIndex+=2;
25
                curOfst=feedItemList.eq(curViewIndex).offset().top-feed2TopPx;
26
            }else{  // 按下k鍵時的處理 (up) 
27
                if(curViewIndex!=-1){
28
                    curViewIndex=curViewIndex>0?curViewIndex:0;
29
                    curOfst=feedItemList.eq(curViewIndex).offset().top-feed2TopPx;
30
                }
31
            } 
32
            $('body,html').animate({ scrollTop: curOfst}, 100);
33
        }                    
34
    }else{
35
        $(this).unbind(eventNS);
36
    }
37
});

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.