javascript - 无法使用 'in' 运算符在未定义中搜索 'backgroundPositionX'

标签 javascript jquery

不明白为什么会发生这种事。

var thumb_width = 240;
var thumb_height = 180;
$('.video-thumbnail').on({
        'mouseenter': function(){
            var i = 0; var j = 0;
            $(this).id = setInterval(function(){
                $(this).animate({
                    'background-position-x': -(j * thumb_width),
                    'background-position-y': -(i * thumb_height)
                });
                i++; j++;
            }, 1000);
        }
    })
});

最佳答案

因为setIntervalWindow上下文中运行。为了修复它,您应该显式提供正确的对象上下文。您有几个选择:

使用$.proxy:

$('.video-thumbnail').on({
    'mouseenter': function() {
        var i = 0; var j = 0;
        $(this).id = setInterval($.proxy(function() {
            $(this).animate({
                'background-position-x': -(j * thumb_width),
                'background-position-y': -(i * thumb_height)
            });
            i++; j++;
        }, this), 1000);
    }
});

或者使用对this的引用:

$('.video-thumbnail').on({
    'mouseenter': function() {
        var i = 0; var j = 0, self = this;
        $(this).id = setInterval(function() {
            $(self).animate({
                'background-position-x': -(j * thumb_width),
                'background-position-y': -(i * thumb_height)
            });
            i++; j++;
        }, 1000);
    }
});

关于javascript - 无法使用 'in' 运算符在未定义中搜索 'backgroundPositionX',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21811582/

相关文章:

javascript - Discord 机器人的特定角色命令

javascript - Angular 2 Aot 错误 : FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

jquery - 可以使用 .attr 创建自定义属性吗?

jQuery 点击函数改变正文溢出属性

javascript - IFrame:在 Chrome 上运行 Iframe 但想要保留 IE 设置

javascript - 如何调用Mapkit js Geocode方法

javascript - 在覆盖层内平滑滚动

javascript - 使用 AJAX 将带有 mySQL 数据的 PHP 变量发送回 javascript

javascript - 如何从动态加载的选择框获取数据

jquery - 光滑的 slider 在动态时仅显示一个点