检测元素外的点击 [英] Detect click outside element
问题描述
如何检测元素外的点击?我正在使用 Vue.js,所以它会在我的模板元素之外.我知道如何在 Vanilla JS 中执行此操作,但我不确定在使用 Vue.js 时是否有更合适的方法?
这是 Vanilla JS 的解决方案:Javascript 检测 div 之外的点击事件
我想我可以使用更好的方式来访问元素?
请注意此解决方案仅适用于 Vue 1.
可以通过设置一次自定义指令很好地解决:
Vue.directive('click-outside', {绑定(){this.event = 事件 =>this.vm.$emit(this.expression, 事件)this.el.addEventListener('click', this.stopProp)document.body.addEventListener('click', this.event)},解除绑定(){this.el.removeEventListener('click', this.stopProp)document.body.removeEventListener('click', this.event)},stopProp(event) { event.stopPropagation() }})
用法:
部分内容
在组件中:
事件:{nameOfCustomEventToCall:函数(事件){//做点什么 - 可能隐藏下拉菜单/模式等.}}
JSFiddle 上的工作演示以及有关警告的附加信息:
https://jsfiddle.net/Linusborg/yzm8t8jq/
How can I detect a click outside my element? I'm using Vue.js so it's gonna be outside my templates element. I know how to do it in Vanilla JS, but I'm not sure if there's a more proper way to do it, when I'm using Vue.js?
This is the solution for Vanilla JS: Javascript Detect Click event outside of div
I guess I can use a better way to access the element?
Keep in attention that this solution only works with Vue 1.
Can be solved nicely by setting up a custom directive once:
Vue.directive('click-outside', {
bind () {
this.event = event => this.vm.$emit(this.expression, event)
this.el.addEventListener('click', this.stopProp)
document.body.addEventListener('click', this.event)
},
unbind() {
this.el.removeEventListener('click', this.stopProp)
document.body.removeEventListener('click', this.event)
},
stopProp(event) { event.stopPropagation() }
})
Usage:
<div v-click-outside="nameOfCustomEventToCall">
Some content
</div>
In the component:
events: {
nameOfCustomEventToCall: function (event) {
// do something - probably hide the dropdown menu / modal etc.
}
}
Working Demo on JSFiddle with additional info about caveats:
https://jsfiddle.net/Linusborg/yzm8t8jq/
这篇关于检测元素外的点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!