簡體   English   中英

iPhone上滾動事件中的SetInterval-為什么此代碼不起作用?

[英]SetInterval inside scrolling events on iPhone - Why this code doesn't work?

請看一下這段代碼(我正在使用Zepto http://zeptojs.com/ BTW)...

var timer = false;

$(window).bind('touchstart touchmove scroll', function (e) {
    if (timer === false) {
        timer = setInterval(function () {
            $('footer').css('top', (this.pageYOffset + this.innerHeight - 40) + 'px');
            console.log('Adjusted...');
        }, 100);
    }
}).bind('touchend', function () {
    clearInterval(timer);
    timer = false;
    console.log('Cleaned it up...');
});

如您所見,我有一個頁腳元素,試圖將其固定在iPhone屏幕的底部。 我知道有像iScroll 4 http://cubiq.org/iscroll-4這樣的庫可以幫助我們輕松實現這一點,但是我試圖查看是否可以簡化它。

事實證明,上面的代碼無法正常工作。 當我實際上在滾動頁面時,出於某種原因,setInterval不會執行,而是堆積在后台以同時運行每個調用。

最后,它並沒有執行我想要的操作,而是要使頁腳“動畫化”,並且不僅在滾動后還要在滾動時將其放置到位。 有誰知道如何以類似的方式實現這種效果?

謝謝!

當您將方法傳遞給setInterval()(或其他任何函數)時,將使用錯誤的this值調用該方法。 此問題在JavaScript參考中進行了詳細說明。

MDC文檔

在外部回調內部, this將是您關心的DOM元素,但是在setInterval回調內部, this將是window 請記住, this是一個關鍵字,而不是變量,並且它與上下文高度相關。

通常的方法是在變量中捕獲this的值,然后使用該變量代替this

if(timer === false) {
    var self = this; // "_that" is also a common name for the variable.
    timer = setInterval(function () {
        $('footer').css('top', (self.pageYOffset + self.innerHeight - 40) + 'px');
        console.log('Adjusted...');
    }, 100);
}

類似的問題也適用於JavaScript中的所有回調,請始終確保您知道this是什么,並掌握其值,並在不需要該值時建立該值的閉包。

暫無
暫無

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

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