只检测伪元素上的点击事件 [英] Only detect click event on pseudo-element

查看:42
本文介绍了只检测伪元素上的点击事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请看这个小提琴:http://jsfiddle.net/ZWw3Z/5/

我的代码是:

p {位置:相对;背景颜色:蓝色;}p:之前{内容: '';位置:绝对;左:100%;宽度:10px;高度:100%;背景颜色:红色;}

 <p>Lorem ipsum dolor sat amet,consectetuer adipiscing 精英.Aenean commodo ligula eget dolor.埃尼马萨.Cum sociis natoque penatibus et magnis disparturient 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>

我只想在伪元素(红色位)上触发点击事件.也就是说,我不希望在蓝色位上触发点击事件.

解决方案

这是不可能的;伪元素根本不是 DOM 的一部分,因此您不能直接将任何事件绑定到它们,只能绑定到它们的父元素.

如果你必须只在红色区域有一个点击处理程序,你必须创建一个子元素,比如span,把它放在开头<p> 标签,将样式应用到 p span 而不是 p:before,并绑定到它.

Please see this fiddle: http://jsfiddle.net/ZWw3Z/5/

My code is:

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>

I would like to trigger a click event only on the pseudo-element (the red bit). That is, I don't want the click event to be triggered on the blue bit.

解决方案

This is not possible; pseudo-elements are not part of the DOM at all so you can't bind any events directly to them, you can only bind to their parent elements.

If you must have a click handler on the red region only, you have to make a child element, like a span, place it right after the opening <p> tag, apply styles to p span instead of p:before, and bind to it.

这篇关于只检测伪元素上的点击事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆