浮动元素导致被遮住元素单击事件不响应

有时候浮动元素会遮住下面元素,并导致下面元素click事件不响应。看如下代码:

<template>
  <Base>
    <div class="btn" @click="onBtn">
      被遮挡button
    </div>
    <div class="left-floating"></div>
  </Base>
</template>

<script>
export default {
  methods: {
    onBtn() {
      alert('没有被遮挡')
    }
  },
};
</script>

<style lang="scss" scoped>
.btn{
  width: 200px;
  height: 50px;
  background: gray;
  position: relative;
}
.btn:hover{
  cursor: pointer;
}
.left-floating {
  width: 90px;
  height: 200px;
  position: absolute;
  left: 0;
  top: -20px;
  background-color: red;
  opacity: 0.3;
}
</style>

运行后效果如下:

点击被红色遮住部分click事件没有响应。有2种方案可解决此问题:

1) 设置被遮住元素z-index

2)给浮动元素设置pointer-events 属性为none, 表示该元素永远不会成为鼠标事件的 target。具体含义可在网上看看。这个属性是CSS3属性,使用时注意浏览器兼容性。

猜你喜欢

转载自blog.csdn.net/liubangbo/article/details/132720364
今日推荐