【问题标题】:increasing clickable area of a button增加按钮的可点击区域
【发布时间】:2013-10-15 07:52:42
【问题描述】:

不寻找任何实际代码,只是指向正确方向的一点。

有没有增加按钮的目标区域但不增加它的大小?例如,我是否可以有效地在按钮周围添加一个 5-10 像素的区域,仍然算作单击按钮。

我见过的所有方法都会增加按钮的实际大小,我不想这样做,因为这会将其他元素推到不合适的位置。我唯一的其他想法是为任何可以确定最近的可点击元素的点击设置一个监听器,如果它在 5-10px 内,则让它触发。

【问题讨论】:

  • 你尝试了什么?贴一段代码

标签: html css button


【解决方案1】:

您可以添加一个伪元素 (: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 &lt;a href="#"&gt;with a link&lt;/a&gt; and &lt;br&gt; other stuff to check if they get pushed around&lt;br&gt; by the size of the link.

【讨论】:

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

有可能,但是有点麻烦,因为您需要引入两个新元素,一个包装器和一个空 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 等元素的活动区域增加到超出其显示区域/控件的范围,这就是您需要其他元素的原因。当然可以检查每次点击是否在按钮范围内,但这要复杂得多。

【讨论】:

  • 这是我想到的第一种方式,我想避免添加额外的包装器。不过谢谢你
【解决方案3】:

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

【讨论】:

    【解决方案4】:

    我不建议尝试增加按钮的可点击区域。如果按钮太小,您可能应该增加整个按钮的大小。触控设备非常擅长帮助用户点击非常小的按钮。

    但是,如果您有一个有意义的用例,那么您可以:

    1) 将按钮放置在 div 内,内边距为 5-10px,然后为该 div 分配一个单击处理程序,该处理程序依次触发其包含的按钮上的单击处理程序。

    或者更简洁的解决方案 - 如果您可以更改当前按钮样式和点击逻辑:

    2) 给按钮一个没有背景或边框和 5-10 像素填充的样式,然后在其中创建一个 div,其样式类似于原始按钮。

    无论哪种方式,您都希望使用带有填充的包含元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多