问题描述
感谢,我们可以使用以下内容用于检测事件支持的JavaScript:
Thanks to Perfection kills, we can use the following JavaScript to detect event support:
function hasEvent(ev) {
var elem = document.createElement('a'),
type = 'on' + ev,
supported = elem[type] !== undefined;
if (!supported) {
elem.setAttribute(type, 'return;');
supported = typeof elem[type] === 'function';
}
elem = null;
return supported;
}
这只适用于我需要的时间:检测 mouseenter
支持; hasEvent('mouseenter')
将在Chrome,Firefox等中返回false。
This works for about the only time I need it: detecting mouseenter
support; hasEvent('mouseenter')
will return false in Chrome, Firefox, etc., as it should.
但是现在我正在尝试修复不支持 focusin
和 focusout
事件的浏览器。 ,这基本上只是Firefox。不幸的是,由于以下原因,Chrome和Safari被列为不完整支持:
But now I'm trying to "fix" browsers that don't support the focusin
and focusout
events. According to PPK, that's basically just Firefox. Unfortunately, Chrome and Safari are listed as having "incomplete" support, for the following reason:
一般情况下,这很好;我只会使用 addEventListener
。然而, 意味着通过 elem.onfocusin!== undefined
检测支持将不起作用。我测试了它,这是真的:
In general, that's fine; I'd only be using addEventListener
anyway. It does mean, however, that detecting support via elem.onfocusin !== undefined
won't work. I tested it out, and it's true:
<p>Do I support <a href="#">focusin</a>?</p>
<script>
var elem = document.getElementsByTagName('p')[0];
// hasEvent method defined here
function listener() {
var response = hasEvent('focusin') ? 'Yes!' : 'No...';
alert(response);
}
elem.addEventListener('focusin', listener, false);
</script>
上述提示否...
in铬!!有没有办法检测浏览器是否支持 focusin
,而不使用浏览器嗅探?
The above alerts No...
in Chrome!! Is there any way to detect whether the browser supports focusin
, without using browser sniffing?
推荐答案
这使用调用 focus()
触发器 focusin
:。
元素必须可见并插入DOM,否则 focusin
由于某种原因不会被触发。
The element must be visible and inserted into the DOM, otherwise focusin
is not fired for some reason.
var result = (function() {
var hasIt = false;
function swap() {
hasIt = true; // when fired, set hasIt to true
}
var a = document.createElement('a'); // create test element
a.href = "#"; // to make it focusable
a.addEventListener('focusin', swap, false); // bind focusin
document.body.appendChild(a); // append
a.focus(); // focus
document.body.removeChild(a); // remove again
return hasIt; // should be true if focusin is fired
})();
这篇关于如何检测`focusin`支持?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!