Change url when manually scrolled to an anchor?

后端 未结 6 1760
失恋的感觉
失恋的感觉 2020-11-30 01:53

By Default, if I have anchors in my website, then the URL on the address bar is changed, when I click on a link (ie. www.mysite.com/#anchor)

Is it possible to change

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 02:42

    Try using this jquery plugin: Scrollorama. It has tons of cool features and you can use window.location.hash to update your browsers hash.

    Alternatively, you can add a "scroll" event to check when an anchor is reached.

    Here is a working fiddle to illustrate the event: http://jsfiddle.net/gugahoi/2ZjWP/8/ Example:

    $(function () {
        var currentHash = "#initial_hash"
        $(document).scroll(function () {
            $('.anchor_tags').each(function () {
                var top = window.pageYOffset;
                var distance = top - $(this).offset().top;
                var hash = $(this).attr('href');
                // 30 is an arbitrary padding choice, 
                // if you want a precise check then use distance===0
                if (distance < 30 && distance > -30 && currentHash != hash) {
                    window.location.hash = (hash);
                    currentHash = hash;
                }
            });
        });
    });
    

提交回复
热议问题