2013-03-23 34 views
3

比方说,您有以下URL(www.domain.com/page.php#_number)。JQuery平滑滚动到URL的标识

我想从url **(_ 1)**中提取id并在页面加载时滚动到它。

您的帮助将不胜感激。

感谢您的帮助。

答案: -

$(document).ready(function() { 
    var $root = $('html, body'); 
    var ancloc = window.location.hash; 
    event.preventDefault(); 
     $root.animate({ 
      scrollTop: $(ancloc).offset().top 
     }, 500, function() { 
      window.location.hash = href; 
     }); 
     return false; 
}); 
+0

[获取与jQuery URL参数](http://stackoverflow.com/questions/1403888/get-url-parameter-with-jquery)。 – Vucko 2013-03-23 12:46:14

+0

我发现'href没有定义' – 2016-01-11 07:46:03

回答

2

为什么不直接使用锚<a href="http://www.domain.com/page.php#number">和动画效果。 检查此链接: Smooth scrolling when clicking an anchor link

+0

您提供的链接仅在点击事件时触发。我想提取id并在页面加载时滚动到它。 – user1852196 2013-03-23 12:44:56

+0

您可以将其更改为您想要的任何事件。我个人使用'$(document).ready(function(e){}'来加载事件。只需删除'.click' – 2013-03-23 12:46:34

1

1您可以通过location.hash得到字符串“#编号”。

2,您可以使用jQuery插件一样jQuery Scrollbar Slider

你并不需要创建点击事件,它处理的是。

编辑:

如果你想让它没有点击运行,在页面加载,你必须阻止默认浏览器的行为。因为浏览器会自动滚动。

here is another DEMO that works on page load DEMO

+0

感谢您的帮助。 – user1852196 2013-03-23 12:55:20