js模拟dom失去焦点,阻止事件冒泡

需求:
  点击div,将mouseListening改变为:true
  点击除div外其他区域,将mouseListening改变为:false
dom
<div class="select-popup_panel" ></div>

js

export default {
  data() {
    return {
      mouseListening: false
    };
  },  
  mounted() {
    this.addListener();
  },
  destroyed() {
    this.removeListener();
  },
  methods: {
     addListener() {
      let self = this;
      let dom = document.getElementsByClassName(‘select-popup_panel‘)[0];
      dom.addEventListener(‘click‘,function(e){
        self.$set(self,‘mouseListening‘,true);
        e.stopPropagation(); // 阻止事件冒泡


     
    //js阻止事件冒泡
       //e.cancelBubble = true;
       //e.stopPropagation();

       //js阻止链接默认行为,没有停止冒泡
       //e.preventDefault(); 
       //return false;

}); document.addEventListener(‘click‘,()=>{self.$set(self,‘mouseListening‘,false)}); }, removeListener() { this.$set(this,‘mouseListening‘,false); let dom = document.getElementsByClassName(‘select-popup_panel‘)[0]; dom.removeEventListener("click", ()=>{}); document.removeEventListener("click", ()=>{}); } } }

 参考:https://www.cnblogs.com/jsanntq/p/7681942.html

js模拟dom失去焦点,阻止事件冒泡

上一篇:JS等概率生成随机整数


下一篇:浅谈MVC三层架构