2013-02-26 51 views
0

我在做週五測驗! 我想使用scrollLeft-jQuery效果來轉到下一個問題。 我以前用過這個沒有問題,但是現在它一直像瘋了一樣跳躍。 我在做什麼錯?ScrollLeft滾動到錯誤的位置

網站:www.carlpapworth.com/friday-quiz/

的HTML:

   <div id="qWrap"> 
        <ul id="qBox"> 
    <!--Q1-->   <li id="q1" class="qContainer"> 
         <div class="qQuestion"><?php echo $Q1; ?> 
         </div> 
         <ul class="qAnswers"> 
          <li><a href="#q2" class="<?php echo $Q1aClass; ?>"><h3><?php echo $Q1a; ?></h3></a></li> 
          <li><a href="#q2" class="<?php echo $Q1bClass; ?>"><h3><?php echo $Q1b; ?></h3></a></li> 
          <li><a href="#q2" class="<?php echo $Q1cClass; ?>"><h3><?php echo $Q1c; ?></h3></a></li> 
         </ul> 
        </li> 
<!--Q2-->   <li id="q2" class="qContainer"> 
         <div class="qQuestion"><?php echo $Q2; ?> 
         </div> 
         <ul class="qAnswers"> 
          <li><a href="#q3" class="<?php echo $Q2aClass; ?>"><h3><?php echo $Q2a; ?></h3></a></li> 
          <li><a href="#q3" class="<?php echo $Q2bClass; ?>"><h3><?php echo $Q2b; ?></h3></a></li> 

          <li><a href="#q3" class="<?php echo $Q2cClass; ?>"><h3><?php echo $Q2c; ?></h3></a></li> 
         </ul> 
        </li> 
    </ul> 
    </div> 

CSS:

#qWrap{ 
width: 480px; 
height: 260px; 
margin: 0 auto; 
overflow: scroll; 
} 

#qBox{ 
width: 1100%; 
height: 260px; 
display: block; 
} 


li.qContainer { 
position: relative; 
width: 9%!important; 
height: 260px!important; 
padding: 0px 0px; 
margin: 0 50px 0 0px; 
float: left; 
} 


.qQuestion { 
width: 480px; 
height: 50px; 
padding: 10px 0px; 
font-family: corbel; 
font-size: 28px; 
text-align: center; 
color: #ffffff; 
} 

JS:

$(document).ready(function() { 
    $('.qAnswers li a').bind('click',function(event){ 
         var $anchor = $(this); 
         $('#qWrap').stop().animate({ 
          scrollLeft: $($anchor.attr('href')).offset().left 
         }, 2000); 
         event.preventDefault(); 
        }); 
}); 

回答

1

您生成的標記不好。在控制檯中查看源代碼。僞標記如下:

<qwrap> 
    <qbox> 
    <li.qcontainer /> 
    <q2 /> 
    <li.qcontainer> 
     <q3 /> 
    </li.qcontainer> 
    </qbox> 
</qwrap> 

如果您還運行以下查詢,您將看到他們爲什麼滾動到不同的位置。由於標記是關閉的,offset是根據不同的offsetParent針對問題進行計算,因此它不一致地滾動。

$('#q2').offsetParent(); 
$('#q3').offsetParent(); 

修復您的標記,並且您的滾動問題消失。

編輯:一旦你的標記是正確的,那麼你可以通過檢查position屬性來計算有多遠滾動qWrapoffset與文檔相關,而position將報告相對於父文件的偏移量。請參閱http://api.jquery.com/position/

position: relative添加到qBox。這將使position相對於正在滾動問題的框。

然後你的代碼幾乎是你已經有的,除了將offset更改爲position

$(document).ready(function() { 
    $('.qAnswers li a').bind('click',function(event){ 
         var $anchor = $(this); 
         $('#qWrap').stop().animate({ 
          scrollLeft: $($anchor.attr('href')).position().left 
         }, 2000); 
         event.preventDefault(); 
        }); 
}); 
+0

我試圖修復標記(請參閱編輯),它仍然無法正常工作。還是我誤解了你的答案? – 2013-02-26 20:32:32

+0

@CarlPapworth請參閱修改。現在你的標記是正確的,我可以進一步觀察你的問題。 – 2013-02-26 20:44:55

+0

非常感謝!你的幫助一直很虔誠! – 2013-02-26 21:40:30

0

在你的.stop(),把

.stop(true, true).animate 

看看能否幫到你。