有使用JS庫如jQuery,Mootools的,原型等
下面的例子是關於純JavaScript平滑滾動的許多例子。如果你在頁面上沒有jQuery/Mootools/Prototype,或者你不想用重JS庫來重載頁面,那麼這個例子會有幫助。
http://jsfiddle.net/rjSfP/
HTML部分:
<div class="first"><button type="button" onclick="smoothScroll(document.getElementById('second'))">Click Me!</button></div>
<div class="second" id="second">Hi</div>
CSS部分:
.first {
width: 100%;
height: 1000px;
background: #ccc;
}
.second {
width: 100%;
height: 1000px;
background: #999;
}
JS部分:
window.smoothScroll = function(target) {
var scrollContainer = target;
do { //find scroll container
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do { //find the top of target relatively to the container
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
scroll = function(c, a, b, i) {
i++; if (i > 30) return;
c.scrollTop = a + (b - a)/30 * i;
setTimeout(function(){ scroll(c, a, b, i); }, 20);
}
// start scrolling
scroll(scrollContainer, scrollContainer.scrollTop, targetY, 0);
}
添加鏈接到jsfiddle沒有任何嘗試的代碼根本沒有任何幫助,顯示你已經嘗試過,至少在詢問之前搜索類似的問題...! –
我試過了一堆不同的方法,其中沒有一個可以工作,所以我把它們扔了出去。 :/ –
這應該會對你有所幫助:: http://stackoverflow.com/questions/3432656/scroll-to-a-div-using-jquery –