简体   繁体   English

如何使一小部分 div 可点击

[英]How to make a small section of div clickable

I want to make only a small section of the box accept pointer events (with clicks outside of the section affecting elements behind it) also it can't affect the appearance of the box.我只想让盒子的一小部分接受指针事件(点击影响其后面元素的部分之外的点击),它也不能影响盒子的外观。 Is this possible in Javascript/jQuery or plain CSS?这在 Javascript/jQuery 或纯 CSS 中可能吗?

 .box { background: black; width: 300px; height: 200px; }
 <div class="box"></div>

I tried a clip-path but that altered the appearance and didn't prevent click/pointer events outside of the clip-path .我尝试了一个clip-path但这改变了外观并且没有阻止clip-path之外的点击/指针事件。

For example say I wanted 10px x 10px area of the box in the center to allow pointer events (click, drag, etc.)例如,说我想要 10px x 10px 框的中心区域以允许指针事件(单击、拖动等)

It's not possible to make only a part of an element clickable**;不可能只使元素的一部分可点击**; either it all is or none of it is.要么全是,要么全都不是。 To do what you require create a child element and make that accept the pointer events, something like this:要执行您需要的操作,请创建一个子元素并使其接受指针事件,如下所示:

 $('.click-area').on('click', function(e) { e.preventDefault(); console.log('You clicked the area'); });
 .box { background: black; width: 300px; height: 200px; position: relative; } .box .click-area { display: inline-block; position: absolute; top: 95px; left: 145px; width: 10px; height: 10px; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="box"> <a href="#" class="click-area"></a> </div>

** you could potentially use <map> on an image but that's outdated, ugly, and not good practice ** 您可能会在图像上使用<map> ,但这是过时的、丑陋的,而且不是很好的做法

You can do this like so:你可以这样做:

$(".box").on('click', function(e) {
  var clickableRegion = ... //your clickable region
  var transformedx = ... //transform e.pageX to be relative to your box
  var transformedy = ... //transform e.pageY to be relative to your box
  if (/*test if click point inside clickableRegion*/) {
    e.preventDefault();
    //...
  }
}

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

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