我认为问题在于,当您使用 querySelector 时,您只会获得 first 活动元素。但是你的锚点在树的下方。
更新:有趣的是,我在 Firefox 或 Opera 上什么都没有,但我在 Chrome 上。以下是 Chrome 结果。请参阅下面的更多内容。
考虑 (live copy):
document.addEventListener("mousedown", handler, false);
function handler(e){
console.log(
"event " + e.type + ": " +
Array.prototype.join.call(document.querySelectorAll("*:active")));
}
当我单击锚点时,我会在控制台中看到:
事件 mousedown: [object HTMLHtmlElement],[object HTMLBodyElement],[object HTMLDivElement],http://fiddle.jshell.net/_display/#
注意最后的 URL,这是HTMLAnchroElement 实例的默认toString,由join 触发。
由于querySelectorAll 需要按文档顺序返回元素,如果您想要最具体的活动元素,您将使用最后一个。示例(live copy):
(function() {
document.addEventListener("mousedown",handler, false);
function handler(e){
var active = document.querySelectorAll("*:active");
var specific = active && active.length && active[active.length-1];
display("Most specific active element: " +
(specific ? specific.tagName : "(none)"));
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
在我的例子中(使用 Chrome),我看到了最具体元素的标签名称(如果我单击链接,则为锚点等)。
Chrome 似乎遵循规范,而 Firefox 和 Opera 却没有。来自 CSS3 选择器规范的Section 6.6.1.2:
:active 伪类在用户激活元素时应用。例如,在用户按下鼠标按钮并释放它的时间之间。
在我看来,:active 因此应该适用于上述情况。如果我们使用这个 CSS,这个断言就会被备份:
*:active {
background-color: red;
}
...使用此 JavaScript:
(function() {
document.addEventListener("mousedown", mouseDown, false);
document.addEventListener("mouseup", mouseUp, false);
function mouseDown(){
var active = document.querySelectorAll("*:active");
var specific = active && active.length && active[active.length-1];
display("Mouse down: Most specific active element: " +
(specific ? specific.tagName : "(none)"));
}
function mouseUp() {
display("Mouse up");
}
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
Live Copy
在我尝试过的所有三种浏览器(Chrome、Firefox、Opera)中,当鼠标按下时元素变为红色背景,当我释放它时又变为白色;但 mousedown 处理程序在 Firefox 或 Opera 中看不到 :active 元素,只有 Chrome。
但我不是 CSS 规范律师。 :-)