簡體   English   中英

為屏幕上的位置添加偵聽器

[英]Adding listener for position on screen

我想在我的網站上設置一些東西,當你在頁面底部的15%內滾動時,一個元素從側面跳出來...我不知道如何開始這里...我應該添加一個是否有滾動功能的監聽器?

我正在嘗試重新創建此頁面底部的效果: http//www.nytimes.com/2011/01/25/world/europe/25moscow.html? _ r = 1

更新

我有這個代碼....

     console.log(document.body.scrollTop); //shows 0
     console.log(document.body.scrollHeight * 0.85); //shows 1038.7
     if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
      console.log();
   $('#flyout').animate({
     right: '0'
    },
    5000,
    function() {

   });
     }

當我滾動到頁面底部時, console.log()值沒有改變。 該頁面是我的視口的兩倍。

[ 工作演示 ]

$(document).ready(function () {
  var ROOT = (function () {
    var html = document.documentElement;
    var htmlScrollTop = html.scrollTop++;
    var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
    html.scrollTop = htmlScrollTop;
    return root;
  })();

  // may be recalculated on resize
  var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
  var visible = false;
  var last = +new Date;
  $(window).scroll(function () {
    if (+new Date - last > 30) { // more than 30 ms elapsed
      if (visible && ROOT.scrollTop < limit) {
        setTimeout(function () { hide(); visible = false; }, 1);
      } else if (!visible && ROOT.scrollTop > limit) {
        setTimeout(function () { show(); visible = true; }, 1);
      }
      last = +new Date;
    }
  });
});

我知道這是一個老話題,但上面收到復選標記的代碼也觸發了$(window).scroll()事件監聽器太多次。

我猜twitter在某個方面也有同樣的問題。 John Resig在這里寫了博客: http//ejohn.org/blog/learning-from-twitter/

$(document).ready(function(){
     var ROOT = (function () {
        var html = document.documentElement;
        var htmlScrollTop = html.scrollTop++;
        var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
        html.scrollTop = htmlScrollTop;
        return root;
    })();

    // may be recalculated on resize
    var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
    var visible = false;
    var last = +new Date;
    var didScroll = false; 

    $(window).scroll(function(){
        didScroll = true; 
    })

    setInterval(function(){
        if(didScroll){
            didScroll = false; 
            if (visible && ROOT.scrollTop < limit) {
                hideCredit(); 
                visible = false; 
            } else if (!visible && ROOT.scrollTop > limit) {
                showCredit(); 
                visible = true; 
            }
        }
    }, 30);


    function hideCredit(){
        console.log('The hideCredit function has been called.');
    }

    function showCredit(){
        console.log('The showCredit function has been called.');
    }
});

因此,兩個代碼塊之間的區別在於調用定時器的時間和方式。 在這段代碼中,計時器被稱為蝙蝠。 因此,每30分鍾,它會檢查頁面是否已滾動。 如果它已被滾動,那么它會檢查我們是否已經通過了我們想要顯示隱藏內容的頁面上的點。 然后,如果檢查為true,則調用實際函數以顯示內容。 (在我的情況下,我剛剛在那里打印出一個console.log。

這似乎比其他解決方案更好,因為最終函數每次迭代只調用一次。 使用另一種解決方案,最終的功能被調用4到5次。 這必須節省資源。 但也許我錯過了一些東西。

抓住滾動事件的好主意,最好使用計時器,每隔幾毫秒檢查滾動位置,如果在你需要的范圍內,那么執行你需要的必要代碼

更新:在過去幾年中,最佳做法是訂閱活動並使用throttle避免過度處理https://lodash.com/docs#throttle

這樣的事情應該有效:

$(window).scroll(function() {
    if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
        // flyout
    }
});

document.body.scrollTop在所有瀏覽器上可能無法正常工作(它實際上取決於瀏覽器和doctype); 所以我們需要在函數中抽象出來。

此外,我們只需要飛行一次。 所以我們可以在飛出后取消綁定事件處理程序。

我們不希望彈出效果減慢滾動速度,因此我們將從事件循環中運行我們的flytout函數(通過使用setTimeout())。

這是最終的代碼:

// we bind the scroll event, with the 'flyout' namespace
// so we can unbind easily
$(window).bind('scroll.flyout', (function() {

    // this function is defined only once
    // it is private to our event handler
    function getScrollTop() {
        // if one of these values evaluates to false, this picks the other
        return (document.documentElement.scrollTop||document.body.scrollTop);
    }

    // this is the actual event handler
    // it has the getScrollTop() in its scope
    return function() {
        if (getScrollTop() > (document.body.scrollHeight-$(window).height()) * 0.85) {
            // flyout
            // out of the event loop
            setTimeout(function() {
                alert('flyout!');
            }, 1);

            // unbind the event handler
            // so that it's not call anymore
            $(this).unbind('scroll.flyout');
        }
    };
})());

所以最后,只有getScrollTop() > document.body.scrollHeight * 0.85在每個滾動事件中執行,這是可以接受的。

彈出效果僅運行一次,並且在事件返回后,因此不會影響滾動。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM