jQuery的.offset()。左边有时会返回正确的值,有时会返回0

问题描述:

我正在用幻灯片的站点。我制作了两个div,一个宽度等于屏幕宽度,另一个宽度等于屏幕宽度的9倍(用于9张幻灯片)jQuery的.offset()。左边有时会返回正确的值,有时会返回0

我使用.offset().left来设置正确的值,并且一般情况下,我的网站工程很好,但有时,它仍然存在

我已经发现了什么问题。我打印.offset().left值代入的console.log,它看起来像

Refresh no.1: 0 
Refresh no.2: 0 
Refresh no.3: 1920 
Refresh no.4: 0 
Refresh no.5: 1920 
Refresh no.6: 1920 
Refresh no.7: 0 
Refresh no.8: 1920 
Refresh no.9: 0 
Refresh no.10: 0 
Refresh no.11: 0 

有时是正确的,有时不是,我不知道为什么。

+0

欢迎来到Stack Overflow!考虑阅读这篇文章对如何问最好的方式问题更快得到帮助。 https://stackoverflow.com/help/how-to-ask – Aaron

好吧,这是解决了,留下,如果有人有同样的问题。 看来,尽管使用

$(document).ready 

的它是在页面之前计算的偏移会是什么,我不得不这样做完全地加载

是替换此:

$(document).ready(function(){ 
     $something1 = $('#something1').offset().left; 
     $something2 = $('#something2').offset().left; 
     $something3 = $('#something3').offset().left; 

有了这个

$(document).ready(function(){ 
    $k = 1; 
    $('#right').on('click',function(){ 
       if($k == 1){ 
        $something1 = $('#something1').offset().left; 
        $something2 = $('#something2').offset().left; 
        $something3 = $('#something3').offset().left; 
        $k = 0;