jQuery scrollTop if URL has hash

左心房为你撑大大i 提交于 2020-01-14 03:21:06

问题


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

        });
    }
});

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?

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.


回答1:


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

        });
    }
});


来源:https://stackoverflow.com/questions/7866629/jquery-scrolltop-if-url-has-hash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!