在外部单击时,Div(包含项目列表)未关闭

时间:2019-04-27 12:46:18

标签: vue.js

请打开https://jsfiddle.net/gfmyt9u8/31/

当用户在<section>标签区域之外单击时,应关闭打开的div覆盖面板。

产生场景的步骤

  • 点击“请选择选项”
  • 现在,在打开的覆盖面板中单击第一项(这样做,面板将自动关闭)
  • 接下来,再次点击蓝色边框div(这将显示“请选择选项”作为标签)
  • 现在,尝试单击“ 蓝色边框div ”和“ 下面打开的div覆盖面板” 两者
  • 覆盖面板不会关闭

实际结果:重叠面板未关闭

预期结果:在“蓝色边框div”和“打开覆盖面板”之外单击时,覆盖面板应关闭  在下面”

1 个答案:

答案 0 :(得分:1)

使用mounted生命周期钩子添加click事件侦听器,以检查click事件是否在元素外部,并基于该元素隐藏元素。

工作示例:

new Vue({
  el: '#app',
  data: {
    displayList: false,
    cat: ['A', 'B']
  },
  methods: {
    itemSelect(o) {
      this.displayList = false;
    }
  },
  mounted: function () {
    
    // Listen to all clicks on the document
    document.addEventListener("click", function(event) {
    
      // If the click inside the element, do nothing
      if (event.target.closest(".section-main")) return;

      // If the clicks outside the element, hide it!
      this.displayList = false;

    }.bind(this));
  }
});
.display-no-selected {  
  cursor: text;
  width: 300px;
  height: 25px;
  border: solid 2px blue;
}
.display-list {
  border: solid 1px wheat;
  width: 300px;
  max-height: 150px;
  overflow-y: auto;
}
.toggle-list {
  display: none;
}
ul, .selected-ul {
  list-style-type: none; 
  margin: 0;
  padding: 0; 
}
ul.inner-ul li {
  cursor: pointer;
  font-weight: normal;
}
ul.inner-ul li:hover {
  background-color: wheat;
}
.default-highlight {
  background-color: wheat;
}
ul.inner-ul li span {
  margin-left: 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
 <section class="section-main">
  <div class="display-no-selected" @click="displayList=true"> Please Select Options 
  </div>
  <div class="display-list"
       v-bind:class="{'toggle-list': !displayList}">
    <ul class="inner-first-ul inner-ul">
      <li v-for="o in cat" @click="itemSelect(o)">
        <span>{{o}}</span>              
      </li>
    </ul>
  </div>
 </section>
</div>