js阻止事件的默认行为发生的三种方式

a标签点击跳转  鼠标右键弹出菜单  滑动滚轮控制滚动条等 这些都是事件的默认行为,某些时候我们不需要这些行为,就需要阻止这些默认行为
阻止事件默认行为
    用on方式添加事件  
        直接在事件处理函数中return false
    用addEventListener绑定事件
        使用  事件对象.preventDefault()
    用attachEvent 绑定事件
        使用  事件对象.returnValue = false 

//=====示例============以右击事件为例
//如果事件 用 on的方式添加  就使用return false 来阻止
document.oncontextmenu = function(){
    console.log('我点击右键了');
    return false;
}
 
//如果事件  用 addEventListener绑定  就使用 事件对象.preventDefault来阻止
document.addEventListener('contextmenu',function(e){
    //打印内容
    console.log('我爱你塞北的雪');
    var ev = window.event || e;
    ev.preventDefault();//阻止事件默认行为
})
 
//如果事件  用 attachEvent绑定  就使用  事件对象.returnValue = false;
document.attachEvent('oncontextmenu',function(e){
	console.log('我爱你亲爱的姑娘');
	var ev = window.event || e;
	ev.returnValue = false;//阻止事件的默认行为
})

猜你喜欢

转载自blog.csdn.net/JackieDYH/article/details/107891812
今日推荐