我想要做的是,当你点击一个按钮时,它会(平滑地)向下滚动到页面上的特定div。
我需要的是,如果你点击按钮,它会平滑地滚动到div 'second‘。
.first {
width: 100%;
height: 1000px;
background: #ccc;
}
.second {
width: 100%;
height: 1000px;
background: #999;
}
<div class="first"><button type="button">Click Me!</button></div>
<div class="second">Hi</div>
发布于 2013-08-06 11:11:08
执行以下操作:
$("button").click(function() {
$('html,body').animate({
scrollTop: $(".second").offset().top},
'slow');
});
更新的Jsfiddle
发布于 2013-08-06 12:30:13
使用jQuery、Mootools、Prototype等JS库进行平滑滚动的例子有很多。
以下示例是在纯JavaScript上实现的。如果你在页面上没有jQuery/Mootools/Prototype,或者你不想用繁重的JS库来重载页面,这个例子将会很有帮助。
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);
}
发布于 2020-02-14 02:15:38
如果你使用scrollIntoView函数怎么办?
var elmntToView = document.getElementById("sectionId");
elmntToView.scrollIntoView();
也有{behavior:"smooth"} ....;) https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
https://stackoverflow.com/questions/18071046
复制相似问题