2010-11-26 61 views
1

我正在尝试编写一个程序,其中基本上用户点击图像,然后图像将向右移动25px。当我点击它时图像会移动,但我试图添加一段代码,当图像通过窗口的右侧时,图像会返回到窗口的左侧。我试过在动画过程中使用If语句,但它似乎不起作用。以下是我的:关于if语句和位置移动的jQuery问题

$('#image').click(function() { 
$(this).animate({ 
    left: '+=155', 
function() { 
    if ($(this).left > $(document).width) { 
$(this).left = 0 
    } 
    }; 

    }); 

});


我使用错误的语法还是我的功能错误?谢谢你的帮助。

回答

1

我会做到这一点...

$('#image').click(function() { 

    $(this).animate({ 
      left: '+=155', 
      function() { 
       if ($(this).offset().left > $(document).width) { 
        $(this).css({ left: 0 }); 
       } 


     }); 
}); 

但实际上它会更好,加入移动像素原来的left第一,并确保不超过宽度。在那种情况下,return false并且根本不移动元素。

您可能还希望在计算偏移量之前将#image的宽度添加到偏移量中,否则将不会触发它已经超出,直到元素的最左侧超过。

0

你的持续时间在哪里?

试试这个,

$('#image').click(function() { 
    $(this).animate(
      { 
       left: '+=155' 
      }, 
      5000, 
      function() { 
       if ($(this).left > $(document).width) { 
       $(this).left = 0 
       }  
     ); 
});