在按钮内单击子元素时不会触发父 onClick

aks*_*aks 2 javascript vue.js vuejs2

我有一个dropdown-button带有点击列表的组件。该按钮有一些文本和图标。如果我们小心地单击轮廓上的按钮而不是文本或图标,则会触发单击事件。这是我的组件:

<template lang="html">
<div>
  <button class="button dropbtn" @click="toggleDropdown">
    <span>{{ name }}</span>
    <span class="icon"><i class="fa fa-caret-down"></i></span>
  </button>
  <div v-show="visible" class="dropdown-content is-primary-important">
    <slot>
    </slot>
  </div>
</div>
</template>

<script>
export default {
  props: ['name'],
  data: function() {
    return {
      visible: false
    }
  },
  mounted: function() {
    this.hideDropdownOnClick();
  },
  methods: {
    toggleDropdown: function() {
      // trigged on click of the button
      // make the dropdown visible
      console.log("toggling dropdown");
      this.visible = !this.visible;
    },
    hideDropdownOnClick: function() {
      window.onclick = (event) => {
        console.log(event.target);
        if (!event.target.matches('.dropbtn')) {
          console.log("here", this.visible);
          this.visible = false;
        }
      }
    }
  }
}
</script>

<style lang="css">
/* Dropdown Content (Hidden by Default) */
.dropdown-content {
  position: absolute;
  background-color: #fff;
  min-width: 140px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  padding: 12px 16px;
  text-decoration: none;
  display: block;
}
</style>
Run Code Online (Sandbox Code Playgroud)

我觉得我在这里缺少一些非常基本的东西,有人可以帮助我吗?谢谢。

编辑

正如这个问题的答案所说,这似乎是浏览器的一个错误: 单击按钮文本并释放它时按钮元素未触发单击事件(但仍在按钮内)?

aks*_*aks 10

添加此 CSS 规则为我解决了这个问题:

span {
    pointer-events: none;
}
Run Code Online (Sandbox Code Playgroud)

  • 另一个经典的例子,其中接受的答案比简单的解决方案复杂得多。 (3认同)
  • 这是迄今为止最简单和最有效的答案。谢谢你。 (2认同)