jQuery scrollTop如果URL有哈希 [英] jQuery scrollTop if URL has hash

查看:105
本文介绍了jQuery scrollTop如果URL有哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经编写了这个简单的插件,可以平滑地滚动浏览器窗口并将哈希链接添加到URL.

I have wrote this simple plugin which smooth scrolls the browser window and adds the hash link to the URL.

$.fn.extend({
    scrollWindow: function(options) {
        var defaults = { duration: "slow", easing : "swing" }                 
        var options =  $.extend(defaults, options);
        return this.each(function() {             
            $(this).click(function(e) {
                var target = $(this).attr('href');
                $('html,body').animate({scrollTop: $(target).offset().top}, options.duration, options.easing, function() {
                    location.hash = target;
                });
                e.preventDefault();
            });

        });
    }
});

如何扩展此插件,以便在DOM中存在的URL中包含哈希值的情况下自动向下滚动到页面的某个部分?

How do I extend this plugin so that it auto scrolls down to the section of the page if it has a hash in the URL that exists in the DOM?

尽管我不清楚将其添加到插件中的最佳位置,但我一半了解如何使用window.location.hash来实现此功能.

I half understand how this will work by using the window.location.hash, although I am unclear where is the best to add this inside of the plugin.

推荐答案

将函数存储在单独的变量中,如果哈希存在,则调用该函数.我已经实现了您的请求,使得每次调用$().scrollWindow时都使用当前的location.hash.其他实现遵循相同的原理.

Store the function in a separate variable, and call the function if the hash is existent. I have implemented your request such that the current location.hash is used each time $().scrollWindow is invoked. Other implementations follow the same principle.

$.fn.extend({
    scrollWindow: function(options) {
        var defaults = { duration: "slow", easing : "swing" }                 
        var options =  $.extend(defaults, options);
        var goToHash = function(target){
            $('html,body').animate({scrollTop: $(target).offset().top}, options.duration, options.easing, function() {
                location.hash = target;
            });
        };
        if(location.hash.length > 1) goToHash(location.hash);
        return this.each(function() {             
            $(this).click(function(e) {
                //Remove junk before the hash if the hash exists:
                var target = $(this).attr('href').replace('^([^#]+)#','#');
                goToHash(target);
                e.preventDefault();
            });

        });
    }
});

这篇关于jQuery scrollTop如果URL有哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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