简答:
我做到了。
我为那里的所有小人物写了一个动态使用的函数......
Working example which displays on the page
Working example logging to the console
长答案:
...还是做了。
我花了一段时间才完成,因为页面上并没有真正的伪元素。虽然上面的一些答案在某些情况下有效,但它们都不能既是动态的,也不能在元素的大小和位置都出乎意料的情况下工作(例如绝对定位的元素覆盖父元素的一部分)。我的没有。
用法:
//some element selector and a click event...plain js works here too
$("div").click(function() {
//returns an object {before: true/false, after: true/false}
psuedoClick(this);
//returns true/false
psuedoClick(this).before;
//returns true/false
psuedoClick(this).after;
});
工作原理:
它抓取父元素的高、宽、上、左位置(基于远离窗口边缘的位置),并抓取高、宽、上、左位置(基于边缘父容器)并比较这些值以确定伪元素在屏幕上的位置。
然后它比较鼠标的位置。只要鼠标在新创建的变量范围内,它就会返回true。
注意:
使父元素相对定位是明智的。如果您有一个绝对定位的伪元素,则此功能仅在它基于父级的尺寸定位时才有效(因此父级必须是相对的……也许粘性或固定也可以……我不知道)。
代码:
function psuedoClick(parentElem) {
var beforeClicked,
afterClicked;
var parentLeft = parseInt(parentElem.getBoundingClientRect().left, 10),
parentTop = parseInt(parentElem.getBoundingClientRect().top, 10);
var parentWidth = parseInt(window.getComputedStyle(parentElem).width, 10),
parentHeight = parseInt(window.getComputedStyle(parentElem).height, 10);
var before = window.getComputedStyle(parentElem, ':before');
var beforeStart = parentLeft + (parseInt(before.getPropertyValue("left"), 10)),
beforeEnd = beforeStart + parseInt(before.width, 10);
var beforeYStart = parentTop + (parseInt(before.getPropertyValue("top"), 10)),
beforeYEnd = beforeYStart + parseInt(before.height, 10);
var after = window.getComputedStyle(parentElem, ':after');
var afterStart = parentLeft + (parseInt(after.getPropertyValue("left"), 10)),
afterEnd = afterStart + parseInt(after.width, 10);
var afterYStart = parentTop + (parseInt(after.getPropertyValue("top"), 10)),
afterYEnd = afterYStart + parseInt(after.height, 10);
var mouseX = event.clientX,
mouseY = event.clientY;
beforeClicked = (mouseX >= beforeStart && mouseX <= beforeEnd && mouseY >= beforeYStart && mouseY <= beforeYEnd ? true : false);
afterClicked = (mouseX >= afterStart && mouseX <= afterEnd && mouseY >= afterYStart && mouseY <= afterYEnd ? true : false);
return {
"before" : beforeClicked,
"after" : afterClicked
};
}
支持:
我不知道....看起来 ie 很笨,有时喜欢将 auto 作为计算值返回。如果尺寸在 CSS 中设置,它似乎在所有浏览器中都能正常工作。所以......在你的伪元素上设置你的高度和宽度,并且只在顶部和左侧移动它们。我建议将它用于您认为它不起作用的事情上。比如动画什么的。 Chrome 可以正常工作。