是否有任何纯 html 属性来指定哪个元素应该专注于加载

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1484908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:56:40  来源:igfitidea点击:

Is there any pure-html attribute to specify which element should be focused on load

htmlfocus

提问by olamundo

And if there isn't, is there a good reason why?

如果没有,是否有充分的理由?

回答by John Cavan

This is coming as a part of HTML 5, so the lack of it in prior version is probably more of an oversight or a case of there being other options lowering the priority.

这是作为 HTML 5 的一部分出现的,因此之前版本中缺少它可能更多是疏忽或存在其他选项降低优先级的情况。

If you're curious, the syntax will be something like:

如果您好奇,语法将类似于:

<input type="text" name="abc" value="" autofocus>

By the standard, it must only be declared once on a page.

按照标准,它只能在一个页面上声明一次。

In the meanwhile, with the state of the nation, you can only really do it with script in the onload event. The easiest way, is to assign the default element on the page a consistent id (call it 'autofocus') and then always set it like:

同时,根据国家的情况,你只能在 onload 事件中使用脚本来真正做到这一点。最简单的方法是为页面上的默认元素分配一个一致的 id(称为“自动聚焦”),然后始终将其设置为:

var a_focus = document.getElementById('autofocus');
if(a_focus) a_focus.focus();

Hope that helps.

希望有帮助。

回答by Chuck

Is TABINDEX=0 not working for you?

TABINDEX=0 对您不起作用吗?

EDIT:

编辑:

Sorry - hurried my answer. TABINDEX=0 will work only if the user hits the "TAB" key. Sorry about that. The following will set focus properly on load. Tested in latest IE, FF, Opera, Safari, & Chrome.

对不起 - 匆忙我的回答。TABINDEX=0 仅在用户点击“TAB”键时才起作用。对于那个很抱歉。以下将在负载上正确设置焦点。在最新的 IE、FF、Opera、Safari 和 Chrome 中测试。

<form>
     <input id="first" tabindex="1" /><br/>
     <input id="second" tabindex="2" />
   <script>
 document.getElementById("first").focus();
   </script>
</form>

回答by bobince

There isn't. There's not really a good reason, other than everyone grew used to using focus()instead. (Unfortunately focus()has drawbacks if the whole page doesn't load and focus straight away.)

没有。没有一个很好的理由,除了每个人都习惯于使用focus()。(不幸的是focus(),如果整个页面没有加载并立即聚焦,则有缺点。)

I would love to see a both default-focus and default-submit-button designation available in HTML, but the browser folk don't seem to be interested. Edit: as John said, this isnow in the HTML5 draft, though there's no implementation yet and HTML5 is far from finalised. We'll see!

我很想在 HTML 中看到默认焦点和默认提交按钮指定,但浏览器人员似乎不感兴趣。编辑:作为约翰说,这现在的HTML5草案,虽然没有实现还和HTML5还远远没有完成。我们拭目以待!

回答by Noon Silk

No.

不。

And probably no good reason; everything seems obvious in hindsight.

并且可能没有充分的理由;事后看来,一切都是显而易见的。