我正在寻找一种技术、示例或库,用于在元素周围提供缓冲区以获取点击和悬停事件。
具体而言,这是针对我希望具有较大点击目标的薄分隔符。
任何想法都会很棒。唯一的要求是它不能影响页面其余部分或其他附近点击区域的样式(最低优先级事件处理程序)。
更新这是我现在所在的位置:
HTML:
<div class="box">
Hi there
<div class="buffer"></div>
</div>
<span class="test">Hi there, I should still be clickable</span>
CSS:
.box {
position: relative;
background: #ccc;
height: 100px;
line-height: 100px;
width: 100px;
text-align: center;
}
.box > .buffer {
position: absolute;
top: -10px;
left: -10px;
background: transparent;
border: 1px solid;
height: 120px;
width: 120px;
}
JS:
var box = document.querySelector('.box');
box.onclick = function(e) {
alert('clicked on buffer')
}
var span = document.querySelector('.test');
span.onclick = function(e) {
alert('clicked on span')
}
JSfiddle:http://jsfiddle.net/ScSEe/
唯一剩下的问题是缓冲区会抑制附近的点击区域。
谢谢!
最佳答案
我找到了一个优雅的解决方案,但它只适用于非 static
定位的元素:
<div id="target" style="position:relative/* for example */; z-index:0;">
<!-- just place this div into the target element: -->
<div style="
z-index:-1; /* placed directly behind parent element */
position:absolute; /* needed for the below to work */
top:-10px; left:-10px; bottom:-10px; right:-10px; /* around the parent */
" />
…
</div>
在那个不可见区域中的点击将被委托(delegate)给父元素,即使它们发生在父元素之外。定位代码使“缓冲区”始终比布局父级(最近的非静态祖先 z-index
)稍大,无论大小或位置如何(也包括动画等)。
关于javascript - 监听事件 "close enough"到元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13864325/