【问题标题】:jQuery question regarding if statement and position moving关于if语句和位置移动的jQuery问题
【发布时间】:2010-11-26 04:46:11
【问题描述】:
我正在尝试编写一个程序,基本上用户单击图像,然后图像将向右移动 25 像素。单击图像时图像会移动,但我尝试添加一段代码,使图像在通过窗口右侧时返回到窗口左侧。我尝试在动画过程中使用 If 语句,但它似乎不起作用。这是我所拥有的:
$('#image').click(function() {
$(this).animate({
left: '+=155',
function() {
if ($(this).left > $(document).width) {
$(this).left = 0
}
};
});
});
是我使用了错误的语法还是我的功能错误?感谢您的帮助。
【问题讨论】:
标签:
jquery
html
css
syntax
jquery-animate
【解决方案1】:
我会这样做...
$('#image').click(function() {
$(this).animate({
left: '+=155',
function() {
if ($(this).offset().left > $(document).width) {
$(this).css({ left: 0 });
}
});
});
虽然确实最好先将移位像素添加到原始left,并确保不超过宽度。在这种情况下,return false 并且根本不要移动元素。
您可能还想在计算之前将#image 的宽度添加到偏移量,否则它不会触发它已经超出,直到元素的最左侧超出。
【解决方案2】:
你的持续时间在哪里?
试试这个,
$('#image').click(function() {
$(this).animate(
{
left: '+=155'
},
5000,
function() {
if ($(this).left > $(document).width) {
$(this).left = 0
}
);
});