jQuery滚动到特定的div位置,以防出现错误和焦点 [英] jquery scroll to specific div position in case of error and focus

查看:85
本文介绍了jQuery滚动到特定的div位置,以防出现错误和焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

非常感谢.

推荐答案

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

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

这篇关于jQuery滚动到特定的div位置,以防出现错误和焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆