背景:

在搜索栏处,搜索关键字,有则弹出一个div,显示内容。

当点击弹出框外的位置时,自动隐藏此弹出框。

如图:

vue实现点击div区域外位置,隐藏div_隐藏div

最重要的部分是这里,添加监听,用完后移除监听

hideDiv() {
var callBack = (e) => {
let hidediv = document.getElementsByClassName("matchresult");
if (hidediv) {
if (!this.$el.contains(e.target)) {
this.matchResult = [];
this.search = "";
document.removeEventListener("click", callBack);
}
}
};
document.addEventListener("click", callBack);
},


整体配置例子

1、vue template区域,搜索结果以a标签展示

<div class="top-search">
<el-input autofocus placeholder="Release相关信息" v-model="search" @change="searchrelease(search)">
</el-input>
</div>
<div class="matchresult" v-if="matchResult.length !== 0">
<div class="innermatch" v-for="(match, index) in matchResult" :key="index">
<a :href="combine_reinfo_url(match)" target="_blank" rel="noopener noreferrer">{{ match.subject }}</a>
</div>
</div>

2、方法部分,每次搜索到结果后才添加这个监听

methods: {
hideDiv() {
var callBack = (e) => {
let hidediv = document.getElementsByClassName("matchresult");
if (hidediv) {
if (!this.$el.contains(e.target)) {
this.matchResult = [];
this.search = "";
document.removeEventListener("click", callBack);
}
}
};
document.addEventListener("click", callBack);
},
searchrelease(val) {
this.matchResult = [];
if (val.toUpperCase().startsWith("LDP")) {
let param = { issueKey: val.toUpperCase() };
Getreleaseinfo(param).then((res) => {
if (res.data.length != 0) {
res.data.forEach((eldata) => {
this.matchResult.push({
subject: eldata.subject.split(" ").pop(),
fix_count: eldata.fix_count,
});
});
this.result = res.data.length;
this.hideDiv();
} else {
this.$message.error("没有找到,请确认是否存在");
}
});
}
}
}

3、css

.matchresult {
z-index: 1;
width: 20%;
height: auto !important;
min-height: 40px;
background-color: #dbe2f0;
border-radius: 8px;
border: 1px solid rgba(219, 226, 240, 1);
box-shadow: 0px 1px 0px 0px rgba(236, 236, 236, 1);
position: absolute;
top: 33px;
right: 70px;
}
.innermatch {
width: 100%;
height: 30px;
margin: 5px 5px 0 10px;
line-height: 30px;
}
.innermatch a {
color: rgba(57, 165, 237, 1);
}