jQuery的:如何滚动到页面加载某些锚/ div?

最近我试图更频繁地使用jQuery,现在我有一些问题,我想用jquery解决希望你能帮助我。

我有一些网页,包括一些锚点标签(可以说,锚点位于页面的中间),并在事件onload我希望页面上启动某个锚点标签的位置意味着页面将“滚动”automaticaly到某个地点。

这是我以前的解决scheme(这是相当丑陋,因为它增加了#i到我的url)

window.onload = window.location.hash = 'i'; 

无论如何,你可以告诉我,我怎么能用jQuery来做到这一点?

注意:我不希望用户在到达此位置时感觉到任何幻灯片或效果

使用下面的简单例子

 function scrollToElement(ele) { $(window).scrollTop(ele.offset().top).scrollLeft(ele.offset().left); } 

其中ele是你的元素(jQuery)..例如: scrollToElement($('#myid'));

没有必要使用jQuery,因为这是原生JavaScriptfunction

 element.scrollIntoView() 

我已经尝试了几个小时,最简单的方法是停止浏览器跳转到锚,而不是滚动到它是:使用另一个锚(一个你不使用在网站上的ID)。 所以,而不是链接到“http://#YourActualID”您链接到“http://#NoIDonYourSite”。 噗,浏览器不会再跳了。

然后检查是否设置了一个锚(使用下面提供的脚本,将其从另一个线程中提取出来)。 并设置你想要滚动的实际ID。

 $(document).ready(function(){ $(window).load(function(){ // Remove the # from the hash, as different browsers may or may not include it var hash = location.hash.replace('#',''); if(hash != ''){ // Clear the hash in the URL // location.hash = ''; // delete front "//" if you want to change the address bar $('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000); } }); }); 

有关工作示例,请参阅http://pro.lightningsoul.com/?c=media&sc=article&cat=coding&id=30#content

看看这个

将#value附加到地址中是IE等浏览器用来标识页面上的已命名的锚点位置的默认行为,看到这来自Netscape。

你可以拦截它并删除它,阅读这篇文章。

  /* START --- scroll till anchor */ (function($) { $.fn.goTo = function() { var top_menu_height=$('#div_menu_header').height() + 5 ; //alert ( 'top_menu_height is:' + top_menu_height ); $('html, body').animate({ scrollTop: (-1)*top_menu_height + $(this).offset().top + 'px' }, 500); return this; // for chaining... } })(jQuery); $(document).ready(function(){ var url = document.URL, idx = url.indexOf("#") ; var hash = idx != -1 ? url.substring(idx+1) : ""; $(window).load(function(){ // Remove the # from the hash, as different browsers may or may not include it var anchor_to_scroll_to = location.hash.replace('#',''); if ( anchor_to_scroll_to != '' ) { anchor_to_scroll_to = '#' + anchor_to_scroll_to ; $(anchor_to_scroll_to).goTo(); } }); }); /* STOP --- scroll till anchror */ 

我是这样做的

 if(location.pathname == '/registration') { $('html, body').animate({ scrollTop: $('#registration').offset().top - 40}, 1000); } 

只需使用scrollTo插件

 $("document").ready(function(){ $(window).scrollTo("#div") }) 

只需附加#[您想要滚动到div的ID]到您的网页url。 这个网页的url是

 http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load 

所以如果我想滚动到版权部分onload,那么该url应该是 –

 http://stackoverflow.com/questions/9757625/jquery-how-to-scroll-to-certain-anchor-div-on-page-load#copyright