检测点击外部元素

JavaScript

StafanItachi

2020-03-10

如何检测元素外部的点击?我正在使用Vue.js,因此它将不在我的模板元素之外。我知道如何在Vanilla JS中做到这一点,但是当我使用Vue.js时,我不确定是否有更合适的方法来做到这一点?

这是Vanilla JS的解决方案:div外部的Javascript Detect Click事件

我想我可以使用更好的方法来访问元素?

第418篇《检测点击外部元素》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

5个回答
宝儿前端 2020.03.10

If you have a component with multiple elements inside of the root element you can use this It just works™ solution with a boolean.

<template>
  <div @click="clickInside"></div>
<template>
<script>
export default {
  name: "MyComponent",
  methods: {
    clickInside() {
      this.inside = true;
      setTimeout(() => (this.inside = false), 0);
    },
    clickOutside() {
      if (this.inside) return;
      // handle outside state from here
    }
  },
  created() {
    this.__handlerRef__ = this.clickOutside.bind(this);
    document.body.addEventListener("click", this.__handlerRef__);
  },
  destroyed() {
    document.body.removeEventListener("click", this.__handlerRef__);
  },
};
</script>
神奇Green 2020.03.10

I create a div at the end of the body like that:

<div v-if="isPopup" class="outside" v-on:click="away()"></div>

Where .outside is :

.outside {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0px;
  left: 0px;
}

And away() is a method in Vue instance :

away() {
 this.isPopup = false;
}

Easy, works well.

蛋蛋卡卡西 2020.03.10

There are already many answers to this question, and most of them are based on the similar custom directive idea. The problem with this approach is that one have to pass a method function to the directive, and cannot directly write code as in other events.

I created a new package vue-on-clickout that is different. Check it out at:

It allows one to write v-on:clickout just like any other events. For example, you can write

<div v-on:clickout="myField=value" v-on:click="myField=otherValue">...</div>

and it works.

神乐阿飞 2020.03.10

You can register two event listeners for click event like this

document.getElementById("some-area")
        .addEventListener("click", function(e){
        alert("You clicked on the area!");
        e.stopPropagation();// this will stop propagation of this event to upper level
     }
);

document.body.addEventListener("click", 
   function(e) {
           alert("You clicked outside the area!");
         }
);
樱Itachi 2020.03.10

社区中有两个软件包可用于此任务(均已维护):

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android