6

The following JQuery code scrolls the page to the first error in the form:

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

However, if I replace the $('html,body') with the name of a container element such as a div class $('.myDivClass') with fixed positioning, it doesn't seem to work well. It just scrolls to random places up and down with each submission. If the container element is anything other than html,body, it doesn't seem to work right.

I can't figure out what I'm doing wrong.

The css of the container element looks like this (so you know what I mean):

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

I have tried using position() instead of offset() for relative positioning but it didn't make a difference.

Thank you!

Update: Looks like there is no solution for this.

4

5 回答 5

13

我知道我迟到了,但遇到了同样的问题,这就是我解决它的方法。

在固定位置的元素内滚动时,出于某种原因,您必须将其自己的 scrollTop 添加到要滚动到的位置,因此:

var position = $errors.filter(":first").position().top + $('. myDivClass').scrollTop()
$('.myDivClass').animate({ scrollTop: position })

为我工作。

于 2014-03-25T14:03:52.343 回答
3

I had the same problem. It works only on first call.

To fix this you need to scroll to the top everytime before calling animate().

So I changed my:

$(element).animate({scrollTop: 500});

with

$(element).scrollTop(0);
$(element).animate({scrollTop: 500});

Yes, it's true, everytime it scrolls to the top first, but without animation and works quite well for me.

Hope it helps.

于 2014-02-11T17:21:52.930 回答
1

如果您滚动的不是窗口,那么您需要找到错误相对于其容器的位置。在这种情况下,一个 div。如果元素在 div 中,则使用position它来引用具有相对、固定或绝对定位的第一个父级。

$('.mcModalWrap1')
     .stop()
     .delay(500)
     .animate({scrollTop: $errors.filter(":first").position().top -30},'slow');
于 2012-02-10T21:51:19.320 回答
0

通过抛弃想法解决了问题。JQuery scrollTop 在 html 之外的父容器中不起作用,body 滚动到特定位置。它仅适用于滚动到顶部或底部。position() 和 offset() 都不能正确计算该值。

如果有人有答案,我很想知道。

于 2012-02-11T09:24:32.920 回答
0

请尝试替换这行代码,看看它的行为是否符合您的要求:

$('#container').stop().delay(500).animate({scrollTop: $errors.filter(":first").offset().top - $('#container').offset().top + $('#container').scrollTop()},'slow');

我相信您可以将零件替换为$errors.filter(":first").offset().top - $('#container').offset().top$errors.filter(":first").position().top

于 2019-07-10T15:58:31.320 回答