按钮可点击区域的增加

16

我不需要实际的代码,只需要指点一下方向。

有没有办法增加按钮的目标区域而不增加它的大小?比如说,我能否在按钮周围有效地添加一个5-10像素的区域,仍然算是点击了按钮。

我看到的所有方法都会增加按钮的实际大小,这是我不想做的,因为这会推动其他元素。 我唯一的想法是监听任何点击事件,确定最近的可点击元素如果在5-10像素以内,则触发它。


1
你尝试了什么?贴一些代码片段。 - Snake Eyes
4个回答

29

您可以添加一个伪元素 (:after / :before),但要小心,因为两个相邻的链接可能会重叠。

<a href="your-link-here" class="big-link">some link text</a>

a.big-link{position:relative;}
a.big-link:before{
    position:absolute;
    content:'';
    top:-10px;
    right:-10px;
    left:-10px;
    bottom:-10px;
}

演示:

a {
  position: relative;
  z-index: 50;
}

a:before {
  position: absolute;
  content: '';
  top: -10px;
  right: -10px;
  left: -10px;
  bottom: -10px;
  outline: 1px solid red;
  z-index: 40;
}
This is some text <a href="#">with a link</a> and <br> other stuff to check if they get pushed around<br> by the size of the link.


3
+1,虽然在这种情况下::before/::after不能用于 inputbutton,是吗? - Zeta
你是对的,它们不会在替换的元素上起作用。我错误地将按钮的提及解释为链接。 - Gabriele Petrioli
1
@Zeta,实际上它适用于 button 但不适用于 input。它在 https://developer.mozilla.org/en-US/docs/Web/HTML/Element/button#Notes 明确说明了这一点。 - Gabriele Petrioli
完美,这正是我想要实现的,谢谢(脱帽致意) - Quince
有人在他们的问题描述中提到了一个按钮,而被接受的解决方案是一个链接,而不是一个按钮。 - plebksig

3
我不建议尝试增加按钮的可点击区域。如果按钮太小,您应该将整个按钮的大小增加。触摸设备非常擅长帮助用户点击即使是非常小的按钮。
然而,如果您有一个合理的使用案例,可以这样做:
1)将按钮放置在一个具有5-10像素填充的div中,然后为div分配一个点击处理程序,以便触发它包含的按钮的点击处理程序。
或者更简洁的解决方案 - 如果您可以更改当前的按钮样式和点击逻辑:
2)给按钮设置没有背景或边框且具有5-10像素填充的样式,然后在其中创建一个与原始按钮样式相同的div。
无论哪种方式,您都需要使用具有填充的包含元素来工作。

0

这是可能的,但有点繁琐,因为您需要引入两个新元素,一个包装器和一个空的 div(fiddle):

/** instead of getting the element by class name, you should
 * get it by ID, so you can do the right action for the right button
 */
document.getElementsByClassName("click-catcher")[0].onclick = function() {
  alert("catched!"); /** you should do something better ;) */
};
/* make it possible to position the catcher */

.button-wrapper {
  position: relative;
}


/* place the button in the foreground */

.button-wrapper>button {
  position: relative;
  z-index: 2;
}


/* give the catcher +1em on all sites*/

.click-catcher {
  position: absolute;
  top: -1em;
  left: -1em;
  right: -1em;
  bottom: -1em;
}
<div class="button-wrapper">
  <div class="click-catcher"></div>
  <!-- this will be styled with CSS -->
  <button>I'm the button :)</button>
</div>

备注

无法将诸如buttoninputvideoaudio等元素的活动区域扩大到它们显示的区域/控件之外,因此您需要额外的元素。当然,可以检查每次点击是否在按钮范围内,但这更加复杂。


这是我最初想到的方法,我想避免添加额外的包装器。谢谢你的建议。 - Quince

-2

只需在按钮上应用与背景相同颜色的边框即可。这将产生放大按钮大小的效果,但仍然显示为您设置的大小。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接