请看这把小提琴:http://jsfiddle.net/ZWw3Z/5/
我的代码是:
p {
position: relative;
background-color: blue;
}
p:before {
content: '';
position: absolute;
left:100%;
width: 10px;
height: 100%;
background-color: red;
}
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate...</p>
我想只在伪元素(红色位)上触发一个单击事件。也就是说,我不希望在蓝色位上触发单击事件。
在现代浏览器中,您可以尝试使用css属性pointer-events(但这导致无法检测父节点上的鼠标事件):
p {
position: relative;
background-color: blue;
color:#ffffff;
padding:0px 10px;
pointer-events:none;
}
p::before {
content: attr(data-before);
margin-left:-10px;
margin-right:10px;
position: relative;
background-color: red;
padding:0px 10px;
pointer-events:auto;
}
当事件目标是“p”元素时,您就知道它是“p:before”。
如果仍然需要检测主p上的鼠标事件,可以考虑修改HTML结构。您可以添加span标签和以下样式:
p span {
background:#393;
padding:0px 10px;
pointer-events:auto;
}
事件目标现在是“span”和“p:before”元素。
不使用jquery的示例:http://jsfiddle.net/2nsptvcu/
jquery示例:http://jsfiddle.net/0vygmnnb/
下面是支持指针事件的浏览器列表:http://caniuse.com/#feat=pointer-events
我的答案将适用于任何想要点击页面特定区域的人。这对我的绝对定位很有效:之后
多亏了这篇文章,我意识到(使用jQuery)我可以使用e.pageY和e.pageX,而不用担心浏览器之间的e.f offsety /X和e.c reenty /X问题。
Through my trial and error, I started to use the clientX and clientY mouse coordinates in the jQuery event object. These coordinates gave me the X and Y offset of the mouse relative to the top-left corner of the browser's view port. As I was reading the jQuery 1.4 Reference Guide by Karl Swedberg and Jonathan Chaffer, however, I saw that they often referred to the pageX and pageY coordinates. After checking the updated jQuery documentation, I saw that these were the coordinates standardized by jQuery; and, I saw that they gave me the X and Y offset of the mouse relative to the entire document (not just the view port).
我喜欢这个活动。pageY的想法,因为它总是相同的,因为它是相对于文档。我可以使用offset()将它与我的:after的父元素进行比较,它返回的X和Y也是相对于文档的。
因此,我可以在整个页面上提出一个永不改变的“可点击”区域范围。
这是我关于codeen的演示。
或者如果懒得用codeen,下面是JS:
我只关心例子中的Y值。
var box = $('.box');
// clickable range - never changes
var max = box.offset().top + box.outerHeight();
var min = max - 30; // 30 is the height of the :after
var checkRange = function(y) {
return (y >= min && y <= max);
}
box.click(function(e){
if ( checkRange(e.pageY) ) {
// do click action
box.toggleClass('toggle');
}
});