【问题标题】:Using jQuery's .focus() to set focus in Firefox on a Mac使用 jQuery 的 .focus() 在 Mac 上的 Firefox 中设置焦点
【发布时间】:2014-11-28 04:03:48
【问题描述】:

我正在尝试让.focus() 在 Mac 上的 Firefox(版本 33.1.1)中工作。一些类似的问题提到了没有视觉效果的具有.focus() 效果的解决方案;在下面的每个测试中,我什至都无法做到这一点。

下面列出的各种测试都适用于 Chrome,但不适用于 Firefox。使用的 HTML 是:

<input type="text" id="test" tabindex="1">

设置tabindex是基于this suggestion,但是好像没有任何效果。

我也考虑过使用autofocus,但这不起作用,因为我需要在用户使用网页时操纵多个字段的焦点,而不仅仅是加载单个字段。

更新Rhumborl 建议below 在使用 iframe 时可能需要 Firefox 处理焦点事件,果然这似乎是问题所在。当您将其从 JSFiddle 的 iframe“编辑小提琴”窗口中取出并全屏查看输出时,以下每个测试都有效。下面我添加了指向每个工作全屏版本的链接。

A. .focus()

$("#test").focus();

Fiddle更新this works in full screen)。

B. setTimeout.focus()

setTimeout(function(){
    $("#test").focus();
},100);

Fiddle更新this works in full screen)。正如建议的hereherehere

C. .trigger('focus')

$("#test").trigger('focus');

Fiddle更新this works in full screen)。正如here建议的那样。

D. setTimeout.trigger('focus')

setTimeout(function(){
   $("#test").trigger('focus');
},100);

Fiddle更新this works in full screen)。正如here建议的那样。

E.纯 JavaScript

document.getElementById("test").focus();

Fiddle更新this works in full screen)。

F. setTimeout 使用纯 JavaScript

setTimeout('document.getElementById("test").focus();',100)

Fiddle更新this works in full screen)。正如here建议的那样。

G. .select()

$("#test").select();

Fiddle更新this works in full screen)。正如here建议的那样。

H. setTimeout.select()

setTimeout(function(){
   $("#test").select();
},100);

Fiddle更新this works in full screen)。

这可能是 Mozilla 需要解决的问题(请参阅 here),但似乎确实有解决方法。例如,如果您在 Mac 上的 Firefox 中转到 Google.com,焦点转到 input 字段(我无法弄清楚 Google 是如何做到的,尽管他们似乎正在处理 @987654349 中的焦点@)。

那么有人知道解决方法吗?

【问题讨论】:

  • 您指向的 jQuery 错误报告建议 iframes 使事情变得更糟。幸运的是,我没有 mac,所以如果您使用全屏结果(将 show 添加到 url 的末尾,例如fiddle.jshell.net/vincentpace/n28wpabv/8/show),可以做得更好吗?虽然即使这样缩小了范围,我也不看好我们的机会......
  • @Rhumborl 这似乎是问题所在!请参阅我对上述问题的编辑以及通过添加show/ 查看的全屏版本的链接。如果您将此建议添加为下面的答案,我将接受它作为解决方案。

标签: javascript jquery firefox


【解决方案1】:
<input type="text" id="test" autofocus="autofocus">

如果您将 autofocus 属性添加到输入,它可能会执行您想要执行的操作。

【讨论】:

  • 我考虑过,但我需要在多个输入字段的初始加载后操纵焦点。我将修改我的问题以澄清这一点。
猜你喜欢
  • 2015-10-20
  • 2011-07-16
  • 1970-01-01
  • 1970-01-01
  • 2011-10-26
  • 1970-01-01
  • 1970-01-01
  • 2011-10-10
  • 2014-07-13
相关资源
最近更新 更多