如果URL有哈希,则jQuery scrollTop

我写了这个简单的插件,它平滑地滚动浏览器窗口并将哈希链接添加到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来解决这个问题,虽然我不清楚最好在插件中添加这个内容。

将函数存储在单独的变量中,如果存在哈希值则调用该函数。 我已经实现了您的请求,以便每次调用$().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(); }); }); } });