手动滚动到锚点时更改URL? [英] Change url when manually scrolled to an anchor?

查看:556
本文介绍了手动滚动到锚点时更改URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,如果我的网站中有锚点,那么当我点击链接(即www.mysite.com/#anchor)时,地址栏上的URL就会改变

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)

当我滚动到锚点时,是否可以立即更改地址栏中的URL?或者当我点击一个新锚点时,有一个包含多个锚点的长文档和地址栏上的URL更改?

Is it possible to change the URL in the address bar instantly when I scroll to an anchor? Or have a long document with multiple anchors and the url changes on address bar, when I hit a new anchor?

推荐答案

尝试使用这个jquery插件: Scrollorama 。它有很多很酷的功能,您可以使用 window.location.hash 来更新浏览器哈希值。

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.

这是一个说明事件的工作小提琴:http://jsfiddle.net/gugahoi/2ZjWP/8/
示例:

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;
            }
        });
    });
});

这篇关于手动滚动到锚点时更改URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆