gpt4 book ai didi

javascript - 获取 jQuery 中的顶部元素

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:57:17 24 4
gpt4 key购买 nike

我构建了以特定方式显示错误的高级验证插件。

但是,当用户输入无效时,我滚动页面到验证失败的第一个元素。

是这样的looks :

enter image description here

那么问题出在哪里呢?

我用黑色加粗了 TD

因此您可以看到 Currency textbox 在第一个 TD 上,而 Owner Name textbox 在第二个 TD 上

因此 Currency 文本框 首先 已验证,因此,页面滚动到 Currency 位置而不是 OwnerName 文本框位置。 (如我所愿)

问题:

我怎样才能找到最顶层的元素(假设所有失败的元素都有 .failed 类 - 只是为了简单起见)。

最佳答案

只需遍历每个元素:

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;
}
});

或者,如果您实际上并不关心它是哪个元素,而只是想要滚动位置:

var tops = $failed.map(function() {
return $(this).offset().top;
}).get();

var top = Math.min.apply(null, tops);

注意:代码更正为使用 .offset 而不是 .scrollTop

关于javascript - 获取 jQuery 中的顶部元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15763511/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com