css()函数调用无声地失败?

时间:2011-09-28 08:30:06

标签: javascript jquery

我对css()函数有一个奇怪的问题。这是我的代码片段。

console.log('' + $(this).css('left') + ':' + $(this).css('top'));
console.log('Desired position - ' + return_to_left + ':' + return_to_top);
$(this).css('top', return_to_top + 'px');
$(this).css('left', return_to_left + 'px');
console.log('Finally: ' + $(this).css('left') + ':' + $(this).css('top'));

我在控制台上获得的输出就是这个。

458px:2113px
Desired position - 448px:2102px;
Finally: 458px:2113px;

有人可以建议为什么会这样吗?我尝试过'!important'。没有帮助。

(另外,对于上下文,此代码是动画后回调函数的一部分。它会尝试将元素放回到动画开始之前的位置。)

感谢您的帮助。

3 个答案:

答案 0 :(得分:5)

发现问题!!

此:

console.log('Desired position - ' + return_to_left + ':' + return_to_top);

...输出

Desired position - 448px:2102px;

因此,您的变量return_to_leftreturn_to_top ALREADY最后会有px字符串。

你的css电话看起来像这样:

$(this).css('top', '448pxpx');
$(this).css('left', '2102pxpx');

哪个不行! :p从css调用的末尾删除+ 'px'

答案 1 :(得分:1)

return_to_left和return_to_top已经包含'px',但你是第二次追加它。

$(this).css('top', return_to_top );
$(this).css('left', return_to_left );

答案 2 :(得分:1)

我尝试了你发布的代码。 它奏效了。

你的变量return_to_left和return_to_top是否有可能是“px”?

我把它放在变量中:

return_to_left = 100;

它奏效了。 我认为您的内容将动态保存。 所以如果你通过加载信息     $(本)的CSS( '左')

然后就会出现“px”

尝试使用此代码代替您的代码:

$(this).css('top', return_to_top);
$(this).css('left', return_to_left);

我不知道您的完整代码,但这可能会解决您的问题

相关问题