有一个few好questions此处关于如何确定焦点与文本区域“并发”的位置 onblur
。
但是我还没有找到一个好的跨浏览器方法来确定哪个 anchor 标记被点击导致文本区域触发onblur
、setTimeout
或不触发。 document.activeElement
看起来很有希望,但是,答案似乎恰恰相反,如果没有 setTimeout
,activeElement
是不可靠的。在某些浏览器中,我不断收到作为 activeElement
返回的 body
。
例如: jsFiddle-ige #1 :
HTML
<form>
<input onblur="blurHandler();" type="text" id="spam1"
value="immediate blur check">
<input onblur="blurHandlerTimeout();" type="text" id="spam2"
value="delayed blur check">
<a href="#" id="spam3">X</a>
<br>
</form>
<br>
<hr>
<br>
<div id="logs"></div>
JavaScript
var logs = document.getElementById('logs');
function blurHandler() {
logit(document.activeElement.outerHTML.substr(0, 80));
}
function blurHandlerTimeout() {
setTimeout(function () {
logit(document.activeElement.outerHTML.substr(0, 80));
}, 10);
}
function logit(msg) {
try {
var e = document.createTextNode(msg), // probably a better way, but this does allow html as text
f = document.createElement('div');
logs.insertBefore(e, logs.firstChild);
logs.insertBefore(f, logs.firstChild);
} catch (err) {
alert(err);
}
}
每次出现以下情况时都会出现立即模糊检查文本框的模糊主体元素:
- Safari 5.1.7(这根本无法让我专注于 anchor , Tab 键或单击)
- 火狐18.0.1
- Chrome 24.0.1312.56 m,
将焦点设置为延迟模糊复选框并单击/按 Tab 键进入 anchor 可以得到:
- Chrome:点击 anchor 时的正文
- Chrome: anchor (如果我按 Tab 键进入)
- Safari:主体无论哪种方式
- Firefox:无论如何都是 anchor
IE8 每次都会为我提供每个文本框、延迟处理程序或否的 anchor 。
因此,诚然,有一些方法可以让 anchor 在共享范围级别(例如全局)设置一个 bool 值,并从模糊事件查询中设置一个 bool 值 setTimeout 来查看 anchor [最近]是否获得焦点,但是伙计天哪,这太糟糕了。
也就是说,我做到了,无论给予还是接受,在这里:jsFiddle-ige #2似乎在所有四个中都工作得很好,尽管我担心它会变得疯狂。
有更好的方法吗?我想 jQuery 很好,尽管我更喜欢干净的 JavaScript 解决方案——也就是说,干净的 jQuery 解决方案比复杂的 JavaScript 修复更好。
最佳答案
document.activeElement
的延迟检查只要您在 anchor 标记上指定 tabindex
属性,就可以在所有浏览器中使用。默认情况下,a
没有 Tab 键顺序,因此我认为那些能够在没有该属性的情况下“聚焦”a
的浏览器行为不当。
根据 HTML5 spec :
The tabindex content attribute allows authors to control whether an element is supposed to be focusable, whether it is supposed to be reachable using sequential focus navigation, and what is to be the relative order of the element for the purposes of sequential focus navigation.
(强调我的)
<form>
<input onblur="blurHandler();" type="text" id="spam1"
value="immediate blur check">
<input onblur="blurHandlerTimeout();" type="text" id="spam2"
value="delayed blur check">
<a href="#" id="spam3" tabindex='1'>X</a>
<br>
</form>
<br>
<hr>
<br>
<div id="logs"></div>
更新了 fiddle : http://jsfiddle.net/Y5kcp/4/
在 IE8/9、FF 18.0.1、Chrome 24.0.1312.56 m、Safari 5.17 中测试
这纯粹是猜测,但也许 IE 表现良好是因为 HTML4 spec for tabindex
没有提到“可聚焦性”作为一项功能:
This attribute specifies the position of the current element in the tabbing order for the current document.
在这种情况下,也许遵守 HTML 4 规范的浏览器可以允许 anchor 标记在有或没有 tabindex 属性的情况下具有焦点。
还值得注意的是,document.activeElement
是一项专有的 IE4 功能(请参阅 MDN 文章中有关 document.activeElement
的注释)。也许这就是为什么它可以在 Internet Explorer 中正常运行而不会超时。
关于javascript - 跨浏览器方法确定选择的 anchor 标记会导致文本区域模糊,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14653381/