在某些场景下,咱们但愿点击a标签之后不作跳转,而且能响应a标签绑定的事件,常见方法href设置javascript:;、#### 等,但经测试发现,这几种方式在chrome,ie9上对onbeforeunload事件的触发不一致,这里作个测试和总结。javascript
示例代码里对几种不一样的方式在chrome,ie下做了测试。
-- chrome版本:版本 58.0.3029.110
-- ie版本:9.0.8112css
<!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的触发状况:html
chrome下,href="" 、href="tel"、href="mailto" 都会触发onbeforeunload事件java
ie下:javascript:void(0); javascript:; href="" 都会触发onbeforeunload事件
so,chrome
4.在但愿点击a标签之后不作跳转,而且能响应a标签绑定的事件,而页面绑定了onbeforeunload事件,href="####", 以及不设置href属性这两种方式是安全的。(href="#"会有页面滚动到顶部的效应) 安全
5.可是,若是使用了javascript:;的方式,能够在a标签的响应事件里加上,return false; 或者e.preventDefault() 来解决ie9下频繁弹出页面离开提示的问题测试
1.onebeforeunload is too enthusiastice in ie9 https://stackoverflow.com/que...spa