首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >单击时平滑滚动到特定的div

单击时平滑滚动到特定的div
EN

Stack Overflow用户
提问于 2013-08-06 10:48:43
回答 8查看 427.1K关注 0票数 100

我想要做的是,当你点击一个按钮时,它会(平滑地)向下滚动到页面上的特定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>

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2013-08-06 11:11:08

执行以下操作:

$("button").click(function() {
    $('html,body').animate({
        scrollTop: $(".second").offset().top},
        'slow');
});

更新的Jsfiddle

票数 192
EN

Stack Overflow用户

发布于 2013-08-06 12:30:13

使用jQuery、Mootools、Prototype等JS库进行平滑滚动的例子有很多。

以下示例是在纯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);
}
票数 45
EN

Stack Overflow用户

发布于 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

票数 14
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/18071046

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档