美文网首页
a标签href属性值对onbeforeunload事件的影响

a标签href属性值对onbeforeunload事件的影响

作者: evelynlab | 来源:发表于2017-06-07 14:59 被阅读57次

    背景

    在某些场景下,我们希望点击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>
    

    结论

    比较.png

    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/questions/7263309/onbeforeunload-event-is-too-enthusiastic-in-ie9

    相关文章

      网友评论

          本文标题:a标签href属性值对onbeforeunload事件的影响

          本文链接:https://www.haomeiwen.com/subject/bttafxtx.html