仅检测填充的点击事件 [英] Detecting click event on padding only

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

问题描述

我有一个带有一些填充的HTML元素。我想检测该元素的填充点击。也就是说,我不希望在用户点击内容时触发事件,只是填充内容。

I have an HTML element with some padding. I would like to detect for clicks on that element's padding. That is, I don't want the event to fire when the user clicks on the content, just the padding.

推荐答案

创建内部元素具有100%的高度/宽度,因此它填充整个元素。然后在此事件上注册一个点击事件处理程序,并防止该事件冒泡。

Create an inner element which has 100% height/width so it fills out the whole element. Then register a click event handler on this event and prevent bubbling of the event.

下面是一个示例(使用jQuery): http://jsfiddle.net/ThiefMaster/QPxAp/

Here's an example (using jQuery): http://jsfiddle.net/ThiefMaster/QPxAp/

标记:

<div id="outer">
    <div id="inner"></div>
</div>

和JS代码:

$('#outer').click(function() {
    alert('click');
});

$('#inner').click(function(e) {
    e.stopPropagation();
});

由于事件气泡,内部元素上的click事件首先触及此元素 - 停止其传播将阻止它从未到达外部元素,因此其click事件处理程序只触发如果属于该元素但未被内部元素覆盖的点击。

Since events bubble, the click event on the inner element hits this element first - stopping its propagation will prevent it from ever reaching the outer element, so its click event handler only triggers if the are that belongs to the element but is not covered by the inner element is clicked.

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

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