如果当前焦点/事件元素是 <input type="file" />
,我似乎无法将其作为 jQuery 对象在 Firefox 中获取.它适用于其他输入类型(文本、密码、提交等)和其他元素类型( <select>
、 <textarea>
等)。
HTML
<input type="file" />
Javascript
// Cannot find input type file elements with :focus,
// $focused.length is always 0 in Firefox (tested using FF 10.0.1)
var $focusedTest1 = $(':focus');
// This line throws for Firefox (tested using FF 10.0.1)
// Permission denied to access property 'nodeType'
// @ http://code.jquery.com/jquery-1.7.1.js:108
// in jQuery.fn.init, below "Handle $(DOMElement)"
var $focusedTest2 = $(document.activeElement);
重现步骤
- 使用 Firefox。
- 聚焦文件框:
- 一直按 Tab 键
- 或点击它。
- 在聚焦文件框的同时,尝试从
$(':focus')
中获取结果.
参见 jsFiddle demonstration of getting the id of the focused element - 使用 Firefox 对其进行测试。
有没有人有解决方案来将焦点/事件元素作为适用于 <input type="file" />
的 jQuery 对象获取? ?
解决方案需要完全通用,因为功能是插件的一部分。我将无法控制脚本将在其上运行的页面。
最佳答案
编辑:此解决方案已在 the problem was first found 处实现, 在 EmulateTab .参见 getFocusedElement() .
在停止编写代码后,我自己找到了一个解决方案 - 但它不是一个非常干净的解决方案。它基本上是 same solution @Neil 建议当我第一次写这篇文章时。
尝试 the updated jsFiddle version with focus listeners and try-catch logic在火狐中。它结合了 :focus
、document.activeElement
和跟踪最后一个“已知”焦点元素的文档级焦点监听器。
查找焦点元素的函数
// Comined function to get the focused element trying as long as possible.
// Extra work done trying to avoid problems with security features around
// <input type="file" /> in Firefox (tested using 10.0.1).
function getFocused() {
// Try the well-known, recommended method first.
var $focused = $(':focus');
if ($focused.size() === 0) {
try {
// Fall back to a fast method that might fail.
// Known to fail for Firefox (tested using 10.0.1) with
// Permission denied to access property 'nodeType'.
$focused = $(document.activeElement)
}
catch (error1) {
warnToConsole("Could not use document.activeElement", document.activeElement, error1);
if (lastFocusedElement !== null) {
try {
// As a last resort, use the last known focused element.
// Has not been tested enough to be sure it works as expected.
$focused = $(lastFocusedElement);
} catch (error3) {
warnToConsole("Could not use lastFocusedElement ", lastFocusedElement, error3);
}
}
}
}
return $focused;
}
关注听众
// Keep a reference to the last focused element, use as a last resort.
var lastFocusedElement = null;
function focusInElement(event) {
lastFocusedElement = event.target;
}
function focusOutElement(event) {
lastFocusedElement = null;
}
// Start listeners.
$(function() {
// Start listeners that keep track of the last focused element.
$(document).on("focusin", focusInElement);
$(document).on("focusout", focusOutElement);
});
我不太喜欢这个解决方案,因为它远不如单行 $(':focus')
干净。欢迎其他答案!
关于javascript - $ (":focus") 在 Firefox 中没有为 <input type ="file"/> 返回任何元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9301310/