jquery - 使用 jQuery 查询 "first"文本框的可靠方法

标签 jquery

我有兴趣编写一个非常通用的脚本,我可以将其包含到我的母版页中,该脚本将焦点放在页面上的第一个文本框上,无论页面布局和内容如何。像这样的东西会起作用吗?

$(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/

相关文章:

javascript - 如何为 CSS 编写 jQuery 或 JavaScript 等价物

Javascript/jQuery - 验证表单所需的最少注释数

javascript - html表格让javascript在<td>标签中自动运行

jquery - 如何在 Jquery 中强制 Instagram amazonaws 托管图像的 HTTPS url header

php - $(window).scroll(function () 不再适用于 chrome 和 firefox

jquery - 为什么是:last-child not giving me the results I expect?

jquery - 显示/隐藏 Html TR/TD

jquery - Tapestry 应用程序中的 session 超时 AJAX 错误

javascript - Jquery - 多次点击导致问题

javascript - JQuery 复选框值不起作用