未捕获的TypeError:无法使用'in'运算符在undefined中搜索'marginLeft'

时间:2013-09-16 16:38:33

标签: jquery

这实际上是我上一个问题的继续,但建议重新打开作为一个单独的问题。

我有一个带有三个图像初始化的精灵图像,我想在鼠标悬停图像时每秒更改图像位置

我尝试了什么:
http://jsfiddle.net/377Ja/4/

错误:

Uncaught TypeError: Cannot use 'in' operator to search for 'marginLeft' 
                    in undefined 

1 个答案:

答案 0 :(得分:2)

这是因为this不是你的元素,而是你的回调中的window

这是解决问题的方法:

var myInterval
$(".miniPosterImg").hover(function() {
    var $this = $(this);
    myInterval= setInterval(function(){
        thismarginLeft = $this.css("margin-left").replace(/[^0-9]/g,'');
        if(thismarginLeft < 360){
                thismarginLeft = thismarginLeft-120;
        //}else{
        //      thismarginLeft = 0;
        }
        $this.css("margin-left", thismarginLeft + "px");
    },1000);
}, function(){
    clearInterval(myInterval) ;
});

Demonstration