【问题标题】:jQuery scrollTop if URL has hashjQuery scrollTop 如果 URL 有哈希
【发布时间】:2011-12-13 13:50:16
【问题描述】:

我编写了这个简单的插件,它可以平滑滚动浏览器窗口并将哈希链接添加到 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 中有散列,我如何扩展此插件以便它自动向下滚动到页面部分?

我对使用 window.location.hash 的工作原理有一半了解,尽管我不清楚在插件中添加此功能的最佳位置。

【问题讨论】:

    标签: javascript jquery plugins jquery-plugins


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2011-06-08
      • 2013-04-29
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 2013-03-12
      • 1970-01-01
      • 2015-06-18
      相关资源
      最近更新 更多