在很多的时候通常需要伪元素来修饰一个html节点,比如说上传图片需要一个删除按钮。那么这个伪元素就需要一个删除按钮,那么伪元素如何来获取点击事件呢?其原理都是通过屏蔽的其寄生元素的操作事件,仅在鼠标点击伪元素的时候事件可操作。具体实现方式有两种,
一种是:元素本身:pointer-events: none;禁用点击事件
其伪元素通过pointer-events: auto;启用点击事件,使鼠标只能点击到伪元素
这种实现方式只能是绑定一个事件,如点击图片实现查看,点击伪元素实现删除则不可以实现。而且会导致:hover等鼠标事件失效,所以不推荐使用
第二种是:通过子元素的事件冒泡原理,在子元素事件处理结束后return false,告知父元素事件处理完毕。这样只就屏蔽了父元素接收事件,然后:after伪元素是悬浮在子元素上面的,故点击伪元素的时候触发父元素事件。下面是参考代码,其中li元素包裹img元素,li带有伪元素
$('.import-img-show-list').on('click', 'img', function (e) {
console.log('-子元素点击事件----应用图片-----');
alert('查看图片');
return false;
});
$('.import-img-show-list').on('click', 'li', function (e) {
$(this).remove();
console.log('-父元素(伪元素点击事件)---单机删除');
});
这种实现方式可以绑定一个事件,如点击图片实现在子元素事件中实现查看,点击伪元素在父元素事件中实现删除。
下面是两种事件实现方式的案例,复制粘贴保存为html即可运行。
<style>
.import-img-show-list{
width:300px;
list-style:none;
float:right
}
.import-img-show-list li{
height:150px;
width:100%;
margin-top: 10px;
/**/
}
.import-img-show-list img{
width: 100%;
height:100%;
}
.import-img-show-list li:hover{
border: 2px solid #ff2938;
cursor: default;
}
.import-img-show-list li:hover:after{
content: '\2716';
float: right;
width: 15px;
height: 15px;
padding: 2px 4px;
color: #505739;
position: relative;
top: -100%;
cursor: pointer;
}
body{
width:700px;
}
div{
border:2px solid blue;
width:300px;
float:left;
}
div:after{
pointer-events: auto;
content: '\2716';
float: right;
width: 15px;
height: 15px;
padding: 2px 4px;
color: #505739;
position: relative;
top: -100%;
cursor: pointer;
}
</style>
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$('.import-img-show-list').on('click', 'img', function (e) {
console.log('-----应用图片-----');
alert('查看图片');
return false;
});
$('.import-img-show-list').on('click', 'li', function (e) {
$(this).remove();
console.log('单击删除');
});
$('div').on('click', function (e) {
alert('只能点击伪元素');
});
});
</script>
</head>
<body>
<div style="pointer-events: none;">
元素本身:pointer-events: none;禁用点击事件
其伪元素通过pointer-events: auto;启用点击事件,使鼠标只能点击到伪元素
div:after{
pointer-events: auto;
}
</div>
<ul class="import-img-show-list">
<li><img/></li>
<li><img/></li>
<li><img/></li>
<li><img/></li>
</ul>
</body>