1、vue的写法1
//html
<div id="box" ref="box" style="width:110px;height:110px;background-color:red"></div>
//JS
created(){ document.addEventListener('click',(e)=>{
console.log(this.$refs.box.contains(e.target));
if(!this.$refs.box.contains(e.target)){
this.isShowDialog = false;
}
})
}
2、vue的写法2
// 检查一个鼠标事件是否发生在元素内部(含border,不含box-shadow等)
HTML:
<li v-for="(twonav,indextwo) in nav.child.contentItems" :key="indextwo">
<button :style='{background:twonav.color}' @click.stop="showThree(twonav,twonav.contentItemId)" @mouseover.stop="showTwodDescription(twonav,twonav.contentItemId)" @mouseout.stop ="hideOneDescription()">{{twonav.displayText}}</button>
<div class="describe" :class="returnTwoNum == twonav.contentItemId? 'twoclassdescrption' : ''">
<span v-if="twonav.description"> {{twonav.description}}</span><span v-else>暂无描述信息</span>
</div>
<div class="class-three" :class="returnThreeNum == twonav.contentItemId? 'threeclassdescrption' : ''" >
<div class="threebg">
<p v-for="(threenav,indexthree) in twonav.child.contentItems" :key="indexthree">
<button :style='{background:threenav.color}' @mouseover.stop="showThreeDescription(threenav.contentItemId)" @mouseout.stop ="hideOneDescription()">{{threenav.displayText}}</button>
<span class="describe" :class="returnThreeNums == threenav.contentItemId? 'twoclassdescrption' : ''"><em v-if="threenav.description"> {{threenav.description}}</em><em v-else>暂无描述信息</em></span>
</p>
</div>
</div>
</li>
CSS:
.twoclassdescrption{
display: block !important;
}
JS:
data () {
returnThreeId:"",
},
computed:{
return this.returnThreeId
},
methods:{
//点击二级导航是否显示三级导航信息
showThree(nav,id){
this.returnThreeId = id;
},
isClickOutsideEl(evt, domEl) {
let rect = domEl.getBoundingClientRect();
let clientX = evt.clientX;
let clientY = evt.clientY;
return (
clientX >= rect.left &&
clientX <= rect.left + rect.width &&
clientY >= rect.top &&
clientY <= rect.top + rect.height
);
},
// 是否点击目标区域外 -> 关闭下拉
docClickDebouncer(evt) {
if (!this.isClickOutsideEl(
evt,
this.$el.querySelector(".class-three")
)) {
this.returnThreeId = null;
}
},
},
watch: {
returnThreeNum(val,old){
if(val !== old){
$(document).on("click", this.docClickDebouncer);
} else {
$(document).off("click", this.docClickDebouncer);
}
}
}
3、原生js的写法
// html <div id="box" style="width:110px;height:110px;background-color:red"></div> //js document.addEventListener('click',(e)=>{
alert('zhixing')
var box = document.getElementById('box');
if(box.contains(e.target)){
alert('在内');
}else{
alert('在外');
}
})
4、jq最简单的写法
$(document).click(function(){
$("#element").hide();
});
$("#element").on("click",function(event){
event.stopPropagation();
});