简体   繁体   English

聆听事件“足够接近”元素

[英]Listen to events “close enough” to the element

I'm looking for a technique, example or lib for providing a buffer area around an element to pick up click and hover events. 我正在寻找一种技术,示例或lib,用于在元素周围提供缓冲区以拾取点击和悬停事件。

Specifically this is for a thin separator that I want to have a larger click target. 具体来说,这是针对我希望具有较大点击目标的细隔板。

Any thoughts would be great. 任何想法都会很棒。 The only requirement is that it cannot affect the style of the rest of the page or other nearby click regions (lowest priority event handler). 唯一的要求是,它不能影响页面其余部分或其他附近单击区域的样式(最低优先级事件处理程序)。


Update This is where I'm at: 更新我在这里:

HTML: HTML:

  <div class="box">
      Hi there
      <div class="buffer"></div>
  </div>
  <span class="test">Hi there, I should still be clickable</span>​

CSS: 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: 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/ JSfiddle: http : //jsfiddle.net/ScSEe/

Only remaining issue is that the buffer squelches nearby click regions. 唯一剩下的问题是缓冲区会抑制附近的点击区域。

Thanks! 谢谢!

I found an elegant solution, however it only works with non- static -positioned elements: 我找到了一个优雅的解决方案,但是它仅适用于非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>

Clicks in that invisble area will get delegated to the parent element, even when they happened outside it. 即使该隐身区域之外的点击发生在该隐身区域之外,也会被委派给该父元素。 The positioning code makes the "buffer area" always be a little bigger than the layout parent (closest non-static ancestor with z-index ), no matter of size or position (also when animated etc). 定位代码使“缓冲区”始终大于布局父对象(具有z-index最接近的非静态祖先),而不管其大小或位置(还包括动画等)。

Demo at jsfiddle.net jsfiddle.net上的演示

How about putting an invisible div element at a higher z-index than the rest of the elements to catch these events? 如何将不可见的div元素置于比其他元素更高的z-index处以捕获这些事件?

<div id="click_region" style="z-index:1000; visibility:hidden;"></div>

$("div#click_region").click(function(){/*do yo thang*/};

您可以将元素放置在透明的div中,并设置一些填充作为分隔符区域,然后将click回调附加到父对象。

如何使用CSS :: before和/或:: after伪元素?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM