2014-11-24 130 views

回答

5

有了这个HTML代码:

<a href="#test">link</a> 
<div id="test"></div> 

你能避免滚动div元素,而是通过使用此代码滚动至窗口的顶部:

$("a").on("click", function(e) { 
    e.preventDefault(); 
    window.scrollTo(0, 0); 
}); 

编辑:

您可以尝试添加以下内容:

var firstVisit = true; 
$(window).scroll(function() { 
    if (firstVisit) { 
     window.scrollTo(0, 0); 
     firstVisit = false; 
    } 
}); 
+0

谢谢,但问题不是当我点击任何东西,而是当我“访问”页面。 – drake035 2014-11-24 01:43:39

+0

@ drake035我编辑了答案。不知道它是否是最有效的或最好的方式,但它似乎工作。 – Dim13i 2014-11-24 01:55:14

+0

Thx但它不起作用。 – drake035 2014-11-24 11:03:38

11

你需要做的是存储hashtag供以后使用,然后删除它,以便浏览器没有任何内容可以滚动到。

重要的是,不要将代码的那部分放在$()或$(window).load()函数中,因为它会迟到,并且浏览器已经移动到标记中。

// store the hash (DON'T put this code inside the $() function, it has to be executed 
// right away before the browser can start scrolling! 
var target = window.location.hash, 
    target = target.replace('#', ''); 

// delete hash so the page won't scroll to it 
window.location.hash = ""; 

// now whenever you are ready do whatever you want 
// (in this case I use jQuery to scroll to the tag after the page has loaded) 
$(window).load(function() { 
    if (target) { 
     $('html, body').animate({ 
      scrollTop: $("#" + target).offset().top 
     }, 700, 'swing', function() {}); 
    } 
}); 
+1

我遇到了一个FF错误,我在一个非常长的列表中使用了max-height overflow-y,FF将向下滚动到隐藏节点将在dom中的位置。这只使用了实际代码的前三行(不是注释),并且这改正了我与FireFox的问题。 – wintercyborg 2016-08-24 18:44:37