开发者

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

Please, take a look at this code (I'm using 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...');
});

As you can see, I have a footer element that I'm trying to keep fixed on the bottom of the iPhone screen. I know that there are libraries that helps us make this quite easily like iScroll 4 http://cubiq.org/iscroll-4, but I was trying to see if I could 开发者_StackOverflow中文版make it simpler.

It turns out that the code above doesn't work properly. While I'm actually scrolling the page, for some reason setInterval doesn't execute but instead seems to pile up on the background to run every call at the same time.

At the end it doesn't do what I wanted it to do, which is to "animate" the footer and have it in place during scroll not only after. Does anyone has any idea on how such effect could be achieved on some similar manner?

Thanks!


When you pass a method to setInterval() (or any other function, for that matter), it will be invoked with a wrong this value. This problem is explained in detail in the JavaScript reference.

MDC docs


Inside your outer callback, this will be the DOM element you care about, but inside the setInterval callback, this will be window. Keep in mind that this is a keyword, not a variable, and that it is highly context sensitive.

The usual approach is to capture the value of this in a variable and then use that variable instead of 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);
}

Similar issues apply to all callbacks in JavaScript, always make sure you know what this is and grab its value and build a closure over that value when it won't be what you want.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜