2012-02-08 69 views
1

我有下面的代码片断滚动我表单的第一个错误:JQuery的动画scrollTop的集装箱

$('html,body').stop().delay(500).animate({scrollTop: $errors.filter(":first").offset().top -30},'slow'); 

在我的jQuery验证码年底全块如下所示。如果在提交时出现错误,它会将表单滚动到第一个错误。

var $errors = $(".mcError"); 
if($errors.size() > 0){ 
    if(settings.mcScrollToError){ 
     $('html,body').stop().delay(500).animate({scrollTop: $errors.filter(":first").offset().top -30},'slow'); 
    } 
    return false; 
} 
else{ 
    mcResponse('', false); 
    return true; 
} 

但是,如果我更换$('html,body')用容器元素的名称,如一个div类$('.myDivClass'),它似乎并没有很好地工作。它只是滚动到随机的地方。

容器元素的CSS看起来是这样的(所以你知道我的意思):

.mcModalWrap1{ 
position:fixed; 
top:0; 
bottom:0; 
left:0; 
right:0; 
padding:50px; 
background-image:url(images/overlay.png); 
overflow:auto; 
z-index:999; 
display:none; 
} 

回答

1

.offset()

Get the current coordinates of the first element in the set of matched elements, relative to the document.

来源:http://api.jquery.com/offset/

您想使用.position()得到的相对位置::

Get the current coordinates of the first element in the set of matched elements, relative to the offset parent.

来源:http://api.jquery.com/position

例如:

$('.myDivClass').stop().delay(500).animate({ scrollTop: ($errors.filter(":first").position().top -30) },'slow'); 
+0

我似乎得到了相同的结果。 – user1002039 2012-02-08 21:03:47

+0

你能发布一个链接,以便我可以看到这种行为吗? – Jasper 2012-02-08 21:04:31

+0

对不起,我无法上传文件。虽然我会接受答案。谢谢! – user1002039 2012-02-08 22:10:50