Javascript 基于散列更改设置滚动动画
我目前正在一个网站上工作,该网站使用下面的javascript代码将动画切换到href中的目标元素。当基于代码的历史记录单击后退/前进按钮时,我将如何让代码设置动画Javascript 基于散列更改设置滚动动画,javascript,jquery-animate,hashchange,Javascript,Jquery Animate,Hashchange,我目前正在一个网站上工作,该网站使用下面的javascript代码将动画切换到href中的目标元素。当基于代码的历史记录单击后退/前进按钮时,我将如何让代码设置动画 /* ------ Smooth Scroll ----- */ $(document).ready(function() { "use strict"; $('a[href*=#]').bind('click', function(e) { e.preventDefault(); //preve
/* ------ Smooth Scroll ----- */
$(document).ready(function() {
"use strict";
$('a[href*=#]').bind('click', function(e) {
e.preventDefault(); //prevent the "normal" behaviour which would be a "hard" jump
var target = $(this).attr("href"); //Get the target
// perform animated scrolling by getting top-position of target-element and set it as scroll target
$('html, body').stop().animate({ scrollTop: $(target).offset().top}, 2000, function()
{
location.hash = target; //attach the hash (#jumptarget) to the pageurl
});
return false;
});
});
您需要侦听哈希更改。有很多方法可以做到这一点。您可以轮询哈希更改,或者使用HTML5的历史api和
onhashchange
方法来侦听更改。要做到这一点,最简单的方法可能是使用某种已经兼顾了两者的库。如果您使用jquery,我建议使用插件。如果你正在使用angular js或其他东西,那么寻找那些插件
你会这样做
$(window).hashchange( function(){
// Do the animation here
})
您不再需要在
a
单击时设置动画 你能加入你的HTML,让我们看看它现在是如何工作的吗?Ben Alman为你做了艰苦的工作!我使用jquery hashchange插件将以下内容放入hashchange函数中,但无法使其动画化<代码>$('html,body').stop().animate({scrollTop:$(target.offset().top},2000,function(){location.hash=target;})代码>这是事件,而不是“hashchange”$(窗口)。在('hashchange',function(){