通过不带提交按钮按 Enter 提交表单

2022-01-30 00:00:00 forms html submit

我正在尝试通过按 Enter 提交表单,但不显示提交按钮.如果可能的话,我不想进入 JavaScript,因为我希望一切都可以在所有浏览器上运行(我知道的唯一 JS 方式是事件).

Well I am trying to submit a form by pressing enter but not displaying a submit button. I don't want to get into JavaScript if possible since I want everything to work on all browsers (the only JS way I know is with events).

现在表单如下所示:

<form name="loginBox" target="#here" method="post">
    <input name="username" type="text" /><br />
    <input name="password" type="password" />
    <input type="submit" style="height: 0px; width: 0px; border: none; padding: 0px;" hidefocus="true" />
</form>

效果很好.提交按钮在用户按下回车时起作用,并且该按钮在 Firefox、IE、Safari、Opera 和 Chrome 中不显示.但是,我仍然不喜欢这个解决方案,因为很难知道它是否适用于所有浏览器的所有平台.

Which works pretty well. The submit button works when the user presses enter, and the button doesn't show in Firefox, IE, Safari, Opera and Chrome. However, I still don't like the solution since it is hard to know whether it will work on all platforms with all browsers.

谁能推荐一个更好的方法?或者这已经是最好的了?

Can anyone suggest a better method? Or is this about as good as it gets?

推荐答案

<头>
通知
请不要在 2021+ 年使用它.往下看,选择一个更好、更现代的答案.

试试:

<input type="submit" style="position: absolute; left: -9999px"/>

这会将按钮向左推,离开屏幕.这样做的好处是,当 CSS 被禁用时,你会得到优雅的降级.

That will push the button waaay to the left, out of the screen. The nice thing with this is, you'd get graceful degradation when CSS is disabled.

更新 - IE7 的解决方法

正如 Bryan Downing + 建议的那样,使用 tabindex 防止标签到达此按钮(由 Ates Goral 提供):

As suggested by Bryan Downing + with tabindex to prevent tab reach this button (by Ates Goral):

<input type="submit" 
       style="position: absolute; left: -9999px; width: 1px; height: 1px;"
       tabindex="-1" />

相关文章