css实现按钮扩大点击热区

当按钮比较小的时候,为了使用体验,我们会扩大点击热区,实现代码如下:

(我们用react代码举例,其他的大同小异。)

jsx:

<div className={s.btn} onClick={() =>{...doSomething}}>显示</div

样式文件:

.btn {
  position: relative;

  &:after {
    content: '';
    /* 父元素需要position: relative; */
    position: absolute;
    z-index: 9;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    transform: scale(2);
  }
}

注意
在微信小程序中,希望在Image标签上添加点击事件,错误代码如下:
jsx

<Image
  src={ImgSource.iconExplanation}
  className={s.btn}
  onClick={() => {
    // doSomething...
  }}
/>

css

.btn {
  width: 24rpx;
  height: 24rpx;
  position: relative;

  &:after {
    content: '';
    /* 父元素需要position: relative; */
    position: absolute;
    z-index: 9;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    transform: scale(2);
  }
}

不知为何 微信小程序中给Image添加after,虽然审查元素中after已经显示,但是点击却不起作用,修改后 代码如下:
实现思路:由于 View 标签添加 after 是可以扩大点击范围的,所以将 Image 标签替换为 View,然后使用背景图片的方式实现。
jsx

<View
  className={s.btn}
  style={{ backgroundImage: `url('${ImgSource.iconExplanation}')` }}
  onClick={() => {
    // doSomething...
  }}
/>

css

.btn {
  width: 24rpx;
  height: 24rpx;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  background-position: center;
  position: relative;

  &:after {
    content: '';
    /* 父元素需要position: relative; */
    position: absolute;
    z-index: 9;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    transform: scale(2);
  }
}
posted @ 2021-06-11 18:26  ZerlinM  阅读(229)  评论(0)    收藏  举报