[英]Get the top element in jQuery
I've built advanced validation plugin which shows the errors in a specific way. 我已经构建了高级验证插件,以特定方式显示错误。
However , when a user input is not valid , I scroll the page to the first element that has failed in validation. 但是,当用户输入无效时,我将页面滚动到验证失败的第一个元素。
this is how it looks : 这是它的样子 :
So where is the problem ? 那问题出在哪里?
I've bolded the TD's
in black. 我用
TD's
粗体化了TD's
。
So you can see that Currency textbox
is on the first TD where Owner Name textbox
is on the second TD 因此,您可以看到
Currency textbox
位于第一个TD上,其中Owner Name textbox
位于第二个TD上
so Currency textbox
has validated first , and so , the page scroll to the Currency location and not to the OwnerName text box location . 因此,
Currency textbox
首先进行了验证,因此页面滚动到货币位置,而不是滚动到OwnerName文本框位置。 ( as I wish) (按照我的意愿)
Question : 题 :
How can I find the topmost element ( lets assume that all failed elements has .failed
class - just for simplicity). 我怎样才能找到最顶层的元素(假设所有失败的元素都有
.failed
类 - 只是为了简单起见)。
Just iterate through each of the elements: 只需遍历每个元素:
var $failed = $('.failed');
var top = null; // current "smallest" value
var found = null; // current "topmost" element
$failed.each(function() {
var $this = $(this);
var cur = $this.offset().top;
if (top === null || cur < top) {
found = this;
top = cur;
}
});
Alternative, if you don't actually care which element it is, but just want the scroll position: 另外,如果你实际上并不关心它是哪个元素,而只想要滚动位置:
var tops = $failed.map(function() {
return $(this).offset().top;
}).get();
var top = Math.min.apply(null, tops);
NB: code corrected to use .offset
instead of .scrollTop
注意:代码已更正为使用
.offset
而不是.scrollTop
There is nothing in jQuery built in to give what you want. 内置的jQuery中没有任何内容可以满足您的需求。 You would have to loop through all of the elements and use
offset()
to see which one has the smallest top and left. 您必须遍历所有元素并使用
offset()
来查看哪个元素具有最小的顶部和左侧。
var failed = $(".failed");
var firstElem = failed.eq(0);
var firstPos = firstElem.offset();
failed.splice(0,1);
failed.each( function() {
var elem = $(this);
var pos = elem.offset();
if (pos.top < firstPos.top || (pos.top===firstPos.top && pos.left<firstPos.left) {
firstElem = elem;
firstPos = pos;
}
});
Try this: 尝试这个:
var el;
$.each($(".failed"), function () {
if (!el || el.offset().top > $(this).offset().top) {
el = $(this);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.