通过按Enter键提交表单而无需提交按钮

通过按Enter键提交表单而无需提交按钮

问题描述:

好吧,我试图通过按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).

现在表单看起来像这样:

Right now the form looks like this:

<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>

这很好。提交按钮在用户按下Enter键时起作用,并且该按钮不会在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?

试试:

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

这会将按钮waaay推到屏幕左侧。这样做的好处是,当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" />