如何检测元素外的点击?我正在使用 Vue.js,所以它会在我的模板元素之外。我知道如何在 Vanilla JS 中执行此操作,但我不确定在使用 Vue.js 时是否有更合适的方法来执行此操作?
这是 Vanilla JS 的解决方案:Javascript Detect Click event outside of div
我想我可以使用更好的方法来访问元素?
最佳答案
这是我使用的解决方案,它基于 Linus Borg 的回答并且适用于 vue.js 2.0。
Vue.directive('click-outside', {
bind: function (el, binding, vnode) {
el.clickOutsideEvent = function (event) {
// here I check that click was outside the el and his children
if (!(el == event.target || el.contains(event.target))) {
// and if it did, call method provided in attribute value
vnode.context[binding.expression](event);
}
};
document.body.addEventListener('click', el.clickOutsideEvent)
},
unbind: function (el) {
document.body.removeEventListener('click', el.clickOutsideEvent)
},
});
您使用 v-click-outside
绑定(bind)到它:
<div v-click-outside="doStuff">
您可以在 https://v2.vuejs.org/v2/guide/custom-directive.html#Directive-Hook-Arguments 中找到更多关于自定义指令和 el, binding, vnode 的含义的信息。
关于javascript - 检测点击外部元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36170425/