MisterHe

 

1原生方法

// html

<div id="box" style="width:110px;height:110px;background-color:red"></div>

//js------js的contains方法用来查看dom元素的包含关系,

document.addEventListener(\'click\',(e)=>{
  alert(\'zhixing\')
  var box = document.getElementById(\'box\');
  if(box.contains(e.target)){
    alert(\'在内\');
  }else{
    alert(\'在外\');
  }
})

 

2、 vue 写法

//html

<div id="box" ref="box" style="width:110px;height:110px;background-color:red"></div>

//js  ----ref是vue获取DOM元素的方法,在标签上绑定ref属性,js在组件内部用this.$refs.ref的值,调用。


created(){
  document.addEventListener(\'click\',(e)=>{
    console.log(this.$refs.box.contains(e.target));
    if(!this.$refs.box.contains(e.target)){
      this.isShowDialog = false;
    }
  })
}

原文:https://blog.csdn.net/cxz792116/article/details/79415544

 

3vue

  给最外层的div加个点击事件 @click="userClick=false"

  给点击的元素上面加上:@click.stop="userClick=!userClick" //vue click.stop阻止点击事件继续传播

或者给子元素js事件里

click(e)=>{

  e.stopPropagation();//阻止事件冒泡

  this.userClick = !this.userClick;

}

分类:

技术点:

相关文章: