在项目开发中搜索按钮点击出现搜索框内容,这个时候点击搜索框以外的内容,搜索框隐藏掉,如下所示:
1、源码
2、实现点击其他区域搜索框内容隐藏,如下:
document.addEventListener('click', (e) => {
if (this.$refs.showPanel) {
let isSelf = this.$refs.showPanel.contains(e.target)
if (!isSelf) {
this.searchbox = false
}
}
})
实现原理:
①、首先用ref来定义一个点击区域的范围
②、监听点击事件,点击的时候如果包含ref元素则返回true,否则返回false(即不包含的时候隐藏属性)