嗯,我试图通过按enter键提交一个表单,但没有显示提交按钮。如果可能的话,我不想进入JavaScript,因为我希望所有东西都能在所有浏览器上工作(我所知道的唯一JS方式是事件)。

现在表单看起来是这样的:

<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浏览器中不会显示该按钮。然而,我仍然不喜欢这个解决方案,因为很难知道它是否适用于所有平台和所有浏览器。

谁能提出一个更好的方法?还是说这已经是最好的结果了?


当前回答

另一个没有提交按钮的解决方案:

HTML

<form>
  <input class="submit_on_enter" type="text" name="q" placeholder="Search...">
</form>

jQuery

$(document).ready(function() {

  $('.submit_on_enter').keydown(function(event) {
    // enter has keyCode = 13, change it if you want to use another button
    if (event.keyCode == 13) {
      this.form.submit();
      return false;
    }
  });

});

其他回答

最简单的方法

<input type="submit" style="width:0px; height:0px; opacity:0;"/>
<input type="submit" style="display:none;"/>

这很好,而且它是你想要达到的最明确的版本。

注意,对于其他表单元素,display:none和visibility:hidden是有区别的。

我认为你应该走Javascript路线,或者至少我会:

<script type="text/javascript">
// Using jQuery.

$(function() {
    $('form').each(function() {
        $(this).find('input').keypress(function(e) {
            // Enter pressed?
            if(e.which == 10 || e.which == 13) {
                this.form.submit();
            }
        });

        $(this).find('input[type=submit]').hide();
    });
});
</script>


<form name="loginBox" target="#here" method="post">
    <input name="username" type="text" /><br />
    <input name="password" type="password" />
    <input type="submit" />
</form>

只需要将hidden属性设置为true:

<form name="loginBox" target="#here" method="post">
    <input name="username" type="text" /><br />
    <input name="password" type="password" />
    <input type="submit" hidden="true" />
</form>

这是我的解决方案,在Chrome, Firefox 6和IE7+测试:

.hidden{
    height: 1px;
    width: 1px;
    position: absolute;
    z-index: -100;
}