2013-02-26 52 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 

看看能否帮到你。