- 在新版本浏览器中,e.preventDefault 和 e.returnValue = false都能够阻止默认行为
- 在老版本浏览器中,就需要区分IE浏览器和非IE浏览器了。
e.preventDefault 用于非IE浏览器;e.returnValue = false用于IE浏览器。
- e.returnValue = false在IE8及以下版本,可以实现阻止默认行为;在IE8以上版本的IE则没有效果,不能阻止默认行为。
<form action="#">
账号:<input type="text" name="user">
<br/>
<button>登录</button>
</form>
<a href="https://www.baidu.com">百度</a>
<script>
//阻止a标签的点击后就默认跳转行为
//获取a标签对象
var a1=document.querySelector("a")
a1.onclick=function(e){
var e = e || window.event
//阻止默认行为
return false
e.preventDefault()
e.returnValue=false
//兼容阻止默认行为
e.preventDefault?e.preventDefault():e.returnValue=false
}
//阻止鼠标右键默认行为
document.oncontextmenu=function(e){
return false
}
//阻止表单的默认提交
/*
注:button标签,如果在form表单中出现时,默认是作为提交按钮使用
*/
var btn=document.querySelector('form')
btn.onsubmit=function(e){
var e = e || window.event
return false
}
</script>