jQuery jquery滚动到特定的div位置,以防出现错误和焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8885558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 11:12:06  来源:igfitidea点击:

jquery scroll to specific div position in case of error and focus

jqueryvalidationscrollposition

提问by user1006072

I have a hidden div with specific error messages throughout my form. Before form submit I run a validate routine to check if all the required fields are filled with some text. If not, a div with the class 'redAlert' gets visible right above the text field. I also want the dialog window to scroll right to this position when the error messages are displayed. I know there are quite a few plugins available for doing this but I want to do it using simple Jquery. I am trying to A) Find the first visible div with the class redAlert, b) Find its position by calling the .offset() on this div and then c) calling .scroll() on the window object but I am not getting this to work. Let me know if I am missing something altogether or my syntax is not valid (I've often found myself struggling with syntax error with Jquery). Below is my code. Also - this only find the visible div (assuming there is only one error div at a time) , can you please provide me the selector for finding first visible div with a particular class.

我在整个表单中有一个隐藏的 div,其中包含特定的错误消息。在表单提交之前,我运行一个验证例程来检查是否所有必填字段都填充了一些文本。如果不是,则在文本字段正上方会显示一个带有“redAlert”类的 div。我还希望对话框窗口在显示错误消息时向右滚动到此位置。我知道有很多插件可用于执行此操作,但我想使用简单的 Jquery 来执行此操作。我正在尝试 A) 使用 redAlert 类找到第一个可见的 div,b) 通过在这个 div 上调用 .offset() 来找到它的位置,然后 c) 在 window 对象上调用 .scroll() 但我没有得到这个上班。如果我完全遗漏了某些东西或者我的语法无效,请告诉我(我经常发现自己在使用 Jquery 时遇到语法错误)。下面是我的代码。

var errorDiv = $('.redAlert:visible').attr("id");
var scrollPos = $("#"+errorDiv ).offset();
//alert(scrollPosition); // This alert always says 'null', why ?
$(window).scroll(scrollPos);
//Also tried scrollTo();

Thanks much in advance.

非常感谢。

回答by Vitalii Petrychuk

var errorDiv = $('.redAlert:visible').first();
var scrollPos = errorDiv.offset().top;
$(window).scrollTop(scrollPos);

Demo:http://jsfiddle.net/Cjuve/2/

演示:http : //jsfiddle.net/Cjuve/2/

回答by arc_shiva

I don't think its gonna work out.

我不认为它会成功。

Look at the code I left behind

看我留下的代码

$('html, body').animate({
    scrollTop: ($('.error').first().offset().top)
},500);