我在使用 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;
谁能说明为什么会发生这种情况?我尝试过使用“!重要”进行试验。没有帮助。
(此外,对于上下文,此代码是动画后回调函数的一部分。它会尝试将元素定位回动画开始前的位置。)
感谢您的帮助。
最佳答案
找到问题了!!
这个:
console.log('Desired position - ' + return_to_left + ':' + return_to_top);
输出...
Desired position - 448px:2102px;
因此您的变量 return_to_left
和 return_to_top
末尾已经有 px
字符串。
您的 CSS 调用如下所示:
$(this).css('top', '448pxpx');
$(this).css('left', '2102pxpx');
这是行不通的! :p 从 css 调用的末尾删除 + 'px'
。
关于javascript - css() 函数调用静默失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7580378/