我有兴趣编写一个非常通用的脚本,我可以将其包含到我的母版页中,该脚本将焦点放在页面上的第一个文本框上,无论页面布局和内容如何。像这样的东西会起作用吗?
$(function() {
$("input[type='text']:first").focus();
});
我担心“第一个”只是它使用 jquery 内部使用的任何索引机制找到的第一个文本框,而不是第一个文本框(即屏幕上的最顶部、最左侧)
谢谢!
最佳答案
如果你需要知道的不是基于 tabindex/dom 顺序,而是基于 CSS 位置,那么你可以尝试这样的事情:
var firstBox = null;
$("input[type='text']").each(function()
{
if (firstBox == null) {
firstBox = $(this);
}
else {
if ($(this).offset().top < firstBox.offset().top || ($(this).offset().top == firstBox.offset().top && $(this).offset().left < firstBox.offset().left)) {
firstBox = $(this);
}
}
});
关于jquery - 使用 jQuery 查询 "first"文本框的可靠方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1165569/