如何顺利滚动页面?

Ang*_*ker 2 html javascript css jquery animation

我需要以动画的方式将页面加载到页面上的某个位置.它工作正常(使用jQuery的动画):

$(document).ready(function () {
    $('html, body').animate({
        scrollTop: $('#today').offset().top - 50
    }, 800, "linear");
});
Run Code Online (Sandbox Code Playgroud)

然而,有一点不是很顺利.特别是在移动设备上,它感觉非常生涩.

我已经看到一些CSS动画(使用transitiontransform)非常流畅,但无法弄清楚如何将其应用于页面滚动.是否有可能使用CSS做我想做的事情?

ale*_*nes 5

尝试设置以下css:

<style type="text/css">
    html {
      scroll-behavior: smooth !important;
    }
</style>
Run Code Online (Sandbox Code Playgroud)

您也可以尝试使用vanilla JavaScript而不是jQuery:

function showIt(el_id) {
    var el = document.getElementById(el_id);
    el.scrollIntoView(true, {behavior: "smooth"});
}
showIt('today')
Run Code Online (Sandbox Code Playgroud)

还可以考虑在页面中间添加一个itermediary元素,例如:

<div id="middle" style="display: none;"></div>

function showIt(el_id) {
    var middle_el = document.getElementById('middle');
    var el = document.getElementById(el_id);
    middle_el.scrollIntoView(true, {behavior: "instant"});  // Go to middle directly and then scroll slowly to #today.
    el.scrollIntoView(true, {behavior: "smooth"});
}
showIt('today')
Run Code Online (Sandbox Code Playgroud)

有关scrollIntoView的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView

您可能也会感兴趣:使用overflow时在mobile/ios上滚动速度:如果你在iOS上则滚动