2012-02-08 41 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