背景
在某些场景下,我们愿望点击a标签今后不做跳转,并且能相应a标签绑定的事宜,罕见要领href设置javascript:;、#### 等,但经测试发明,这几种体式格局在chrome,ie9上对onbeforeunload事宜的触发不一致,这里做个测试和总结。
示例代码
示例代码里对几种差别的体式格局在chrome,ie下作了测试。
— chrome版本:版本 58.0.3029.110
— ie版本:9.0.8112
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style type="text/css">
.container {
margin-bottom: 64px;
}
.content {
height: 2000px; /*设置一个比较高的高度,使页面涌现转动条*/
background: #f0f0f0;
}
.item {
margin-top: 12px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
测试a标签
</div>
<div>
<div class="item"><a href="javascript:void(0);" >test1-运用void</a> </div>
<div class="item"><a href="javascript:;" >test2-运用javascript:;</a> </div>
<div class="item"><a href="####" >test3-运用####</a></div>
<div class="item"><a href="#">test4-运用#</a></div>
<div class="item"><a class="">test5-不加href属性</a></div>
<div class="item"><a href="">test6-href属性值为空</a></div>
<div class="item"><a href="tel:18822222222">test7-打电话</a></div>
<div class="item"><a href="mailto:xxx@163.com">test8-发邮件</a></div>
</div>
</div>
</body>
<script type="text/javascript">
window.onbeforeunload = function(e) {
e.returnValue = '';
}
</script>
</html>
结论
1.运用href=”” 与运用href=”#” 结果是一样的,都邑转动到页面顶部
2.a标签不加href属性,不会具有a标签的性子(hover手形,下划线),但能够用css加上标签的默许款式
3.对onbeforeunload的触发状况:
chrome下,href=”” 、href=”tel”、href=”mailto” 都邑触发onbeforeunload事宜
ie下:javascript:void(0); javascript:; href=”” 都邑触发onbeforeunload事宜
so,
4.在愿望点击a标签今后不做跳转,并且能相应a标签绑定的事宜,而页面绑定了onbeforeunload事宜,href=”####”, 以及不设置href属性这两种体式格局是平安的。(href=”#”会有页面转动到顶部的效应)
5.然则,假如运用了javascript:;的体式格局,能够在a标签的相应事宜里加上,return false; 或许e.preventDefault() 来处理ie9下频仍弹出页面脱离提醒的题目
Reference
1.onebeforeunload is too enthusiastice in ie9 https://stackoverflow.com/que…