请打开 https://jsfiddle.net/gfmyt9u8/31/
当用户在标记区域之外单击<section>
时,应关闭打开的div 覆盖面板。
生成场景的步骤:
- 点击"请选择选项">
- 现在,单击打开的覆盖面板中的第一项(通过这样做,面板会自动关闭(
- 接下来,再次单击蓝色边框div(这将"请选择选项"作为标签(
- 现在,尝试在">蓝色边框div"和"打开下面的div覆盖面板">之外单击两者
- 覆盖面板无法关闭
实际结果:覆盖面板未关闭
预期结果:在"蓝色边框div"和"打开覆盖面板"之外单击时,覆盖面板应关闭 下面">
使用 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>