背景
在某些場景下,我們希望點(diǎn)擊a標(biāo)簽以后不做跳轉(zhuǎn),并且能響應(yīng)a標(biāo)簽綁定的事件,常見方法href設(shè)置javascript:;、#### 等,但經(jīng)測試發(fā)現(xiàn),這幾種方式在chrome,ie9上對onbeforeunload事件的觸發(fā)不一致,這里做個(gè)測試和總結(jié)。
示例代碼
示例代碼里對幾種不同的方式在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; /*設(shè)置一個(gè)比較高的高度,使頁面出現(xiàn)滾動(dòng)條*/
background: #f0f0f0;
}
.item {
margin-top: 12px;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
測試a標(biāo)簽
</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-發(fā)郵件</a></div>
</div>
</div>
</body>
<script type="text/javascript">
window.onbeforeunload = function(e) {
e.returnValue = '';
}
</script>
</html>
結(jié)論

1.使用href="" 與使用href="#" 效果是一樣的,都會(huì)滾動(dòng)到頁面頂部
2.a標(biāo)簽不加href屬性,不會(huì)具有a標(biāo)簽的性質(zhì)(hover手形,下劃線),但可以用css加上標(biāo)簽的默認(rèn)樣式
3.對onbeforeunload的觸發(fā)情況:
- chrome下,href="" 、href="tel"、href="mailto" 都會(huì)觸發(fā)onbeforeunload事件
- ie下:javascript:void(0); javascript:; href="" 都會(huì)觸發(fā)onbeforeunload事件
so,
4.在希望點(diǎn)擊a標(biāo)簽以后不做跳轉(zhuǎn),并且能響應(yīng)a標(biāo)簽綁定的事件,而頁面綁定了onbeforeunload事件,href="####", 以及不設(shè)置href屬性這兩種方式是安全的。(href="#"會(huì)有頁面滾動(dòng)到頂部的效應(yīng))
5.但是,如果使用了javascript:;的方式,可以在a標(biāo)簽的響應(yīng)事件里加上,return false; 或者e.preventDefault() 來解決ie9下頻繁彈出頁面離開提示的問題
Reference
1.onebeforeunload is too enthusiastice in ie9 https://stackoverflow.com/questions/7263309/onbeforeunload-event-is-too-enthusiastic-in-ie9