实现点击页面其他地方,隐藏div(原生和VUE)


 

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;

}


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM