2011-02-07 63 views
1

我有一个网站,其特点是“固定”标题,问题是,它真的搞砸了链接,进一步链接下拉页面拉“http://mysite.com/#lower_div_on_the_page”JavaScript来确定页面上的开始滚动位置?

它是甚至可以使用JavaScript来做类似的事情

if (URL has #hashtag) {starting scroll position = normal position + (my_header_height)} 

这甚至有可能吗?

编辑: 感谢所有的答复......真的很感激。作为参考,我肯定使用jQuery ...我怎么用jQuery来做到这一点?

+0

对于将来的问题,如果您使用的是jQuery,请确保它是在标签或问题文本中指定的,这样用户就不会浪费时间回答常见问题。查看我对您需要使用的jQuery API函数的响应,以将功能拼凑在一起。 – 2011-02-07 21:55:33

+0

谢谢,我完全意识到这是我的错,因为没有指定jQuery ... :( – Brian 2011-02-07 21:59:26

回答

1

是的,这是可能的。

这里有你需要采取的步骤:

  • 建立一个DOM Loaded事件处理。有多种方法可以做到这一点,这里有一个link to a web page that explains how to do this。另外,如果您使用的是jQuery(请参阅.ready())或Prototype.js(请参阅observe extension)这样的javascript框架,它会容易得多。

  • 在DOM加载的事件处理函数中解析hashtag的URL(window.location)。

    var hashTag = window.location.href;
    hashTag = hashTag.substr(hashTag.indexOf('#') + 1);
    // now hashTag contains the portion of the URL after the hash sign

  • 然后,如果你认识到锚标记计算基于DOM树或任何逻辑,你想使用该元素的位置所需的滚动位置。同样,jQuery(请参阅.offset())或Prototype.js(请参阅cumulativeScrollOffset)应该能够帮助确定滚动到的正确偏移量。

  • 设置页面的滚动条。再次jQuery(见.scrollTop())或Prototype.js(请参阅scrollTo)都有扩展来帮助解决这个问题。

这里是一个jQuery例如:

$(document).ready(function() { 
    var hashTag = window.location.href; 
    if(hashTag.indexOf('#') > 0) 
    { 
     hashTag = hashTag.substr(hashTag.indexOf('#')); 

     // now get the element's offset relative to the document 
     var offsetTop = $(hashTag).offset().top; 

     // and finally, scroll the document to that offset 
     $(document).scrollTop(offsetTop); 
    } 
}); 
+0

太棒了!...我肯定使用jQuery!如何用jQuery看看? – Brian 2011-02-07 21:53:38

1

当然是,你可以做简单的东西如:

if(window.location.hash != ''){ 
    elementOffset = document.getElementById(window.location.hash.substr(1)).offsetTop; 
    window.scrollTo(0,elementOffset + my_header_height); 
} 

使用jQuery它会显然是简单,你需要根据包含的元素等来获得额外的偏移量,但这应该让你开始。

相关问题