【问题标题】:Input field receives focus after button is clicked in Safari, but not in Chrome在 Safari 中单击按钮后,输入字段获得焦点,但在 Chrome 中没有
【发布时间】:2019-04-23 13:30:43
【问题描述】:

我发现 Chrome 和 Safari 之间存在这种奇怪的行为差异。如果标签里面有输入和按钮,点击按钮会使输入在 Safari 中获得焦点,但在 Chrome 中不会。

我发现将e.preventDefault() 添加到按钮单击处理程序会使 Safari 的行为与 Chrome 相同。

这是最小的代码示例:

<label>
  <input />
  <button>add</button>
</label>

这是 Chrome/Safari 中的错误还是某些记录在案的“功能”?这个 html 应该表现的“正确”方式是什么?

【问题讨论】:

    标签: html google-chrome safari


    【解决方案1】:

    不知道为什么您的按钮位于标签内。输入和按钮都是可操作的(可以在其上执行一些操作)元素。默认情况下,可操作元素在浏览器中获得焦点。因此,您应该将两个元素分开。标签可以被包裹或不能被输入包裹,详情参考“Is it better to wrap the label tag around a form item or use the "for" attribute in HTML?”。

    <body>
    
      <label>
      <input />
    </label>
      <button>add</button>
    </body>

    【讨论】:

    • 如果它解决了您的问题,请接受答案,以便其他人也可以从这篇文章中受益并节省精力。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 2022-01-01
    • 1970-01-01
    • 2014-10-07
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    • 2021-10-14
    相关资源
    最近更新 更多