47

我的代码位于http://jsfiddle.net/mannagod/QT3v5/7/

JS是:

function delay() {
    var INTENDED_MONTH = 7 //August
    // INTENDED_MONTH is zero-relative
    now = new Date().getDate(),
rows = document.getElementById('scripture').rows;
    if (new Date().getMonth() != INTENDED_MONTH) {
        // need a value here less than 1, 
        // or the box for the first of the month will be in Red
        now = 0.5
    };
    for (var i = 0, rl = rows.length; i < rl; i++) {
        var cells = rows[i].childNodes;
        for (j = 0, cl = cells.length; j < cl; j++) {
            if (cells[j].nodeName == 'TD'
  && cells[j].firstChild.nodeValue != ''
  && cells[j].firstChild.nodeValue == now) {
                // 'ffff99' // '#ffd700' // TODAY - red
                rows[i].style.backgroundColor = 'red' 
                rows[i].scrollIntoView();
            }
        }
    }
}

我需要找到一种方法来平滑.scrollintoview(). 现在它“跳转”到突出显示的行。我需要它顺利过渡到该行。它需要动态完成以替换scrollintoview。有任何想法吗?谢谢。

4

8 回答 8

122

在大多数现代浏览器(Chrome 和 Firefox,但不是 Safari、UC 或 IE)中,您可以将对象中的选项传递给.scrollIntoView().

尝试这个:

elm.scrollIntoView({ behavior: 'smooth', block: 'center' })

其他值为behavior: 'instant'orblock: 'start'block: 'end'。请参阅https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

于 2016-03-23T14:03:18.430 回答
39

我也在搜索这个问题并找到了这个解决方案:

$('html, body').animate({
    scrollTop: $("#elementId").offset().top
}, 1000);

资源: http ://www.abeautifulsite.net/smoothly-scroll-to-an-element-without-a-jquery-plugin-2/

于 2015-09-09T15:47:11.530 回答
15

也许你不想仅仅为了实现这个特性而添加 jQuery。elem 是要滚动的元素。可以从要移动到视图中的元素的 offsetTop 属性中获取目标位置。

function Scroll_To(elem, pos)
{
    var y = elem.scrollTop;
    y += (pos - y) * 0.3;
    if (Math.abs(y-pos) < 2)
    {
        elem.scrollTop = pos;
        return;
    }
    elem.scrollTop = y;
    setTimeout(Scroll_To, 40, elem, pos);   
}
于 2013-04-23T13:55:44.867 回答
7

requestAnimationFrame在没有 jQuery 的情况下使用特定持续时间平滑滚动。

演示:http ://codepen.io/Shadeness/pen/XXyvKG?editors=0010

window.bringIntoView_started = 0;
window.bringIntoView_ends = 0;
window.bringIntoView_y = 0;
window.bringIntoView_tick = function() {
  var distanceLeft, dt, duration, t, travel;
  t = Date.now();
  if (t < window.bringIntoView_ends) {
    dt = t - window.bringIntoView_started;
    duration = window.bringIntoView_ends - window.bringIntoView_started;
    distanceLeft = window.bringIntoView_y - document.body.scrollTop;
      travel = distanceLeft * (dt / duration);
      document.body.scrollTop += travel;
      window.requestAnimationFrame(window.bringIntoView_tick);
  } else {
    document.body.scrollTop = window.bringIntoView_y;
  }
};
window.bringIntoView = function(e, duration) {
  window.bringIntoView_started = Date.now();
  window.bringIntoView_ends = window.bringIntoView_started + duration;
  window.bringIntoView_y = Math.min(document.body.scrollTop + e.getBoundingClientRect().top, document.body.scrollHeight - window.innerHeight);
  window.requestAnimationFrame(window.bringIntoView_tick);
};

例如:

bringIntoView(document.querySelector('#bottom'), 400)

它应该随着 (deltaTime) 变大而加速,并随着get 变小dt而减慢。distanceLeft如果用户滚动但我考虑打破循环。全局变量会阻止之前的调用完全接管,但不会取消之前的递归循环,因此它的动画速度会快两倍。

于 2016-02-10T04:03:40.347 回答
4

你只需要包含这个 polyfill 就可以了。

https://github.com/iamdustan/smoothscroll

<script src="js/smoothscroll.js"></script>

或者,如果您使用 npm,则需要它。

require('smoothscroll-polyfill').polyfill();

使用原生 scrollIntoView 方法。

document.getElementById('parallax-group-logo').scrollIntoView({
    block: "start",
    behavior: "smooth"
});
于 2017-05-06T16:56:36.837 回答
2

尝试这个:

function scroll_into_view_smooth(elem)
{   var FPS = 48; // frames per second
    var DURATION = 0.6; // sec
    var e = elem;
    var left = e.offsetLeft;
    var top = e.offsetTop;
    var width = e.offsetWidth;
    var height = e.offsetHeight;
    var body = document.body;
    var to_scroll = [];
    var p, offset;
    while ((p = e.offsetParent))
    {   var client_width = p.clientWidth;
        var client_height = p!=body ? p.clientHeight : Math.min(document.documentElement.clientHeight, window.innerHeight);
        if (client_width<p.scrollWidth-1 && ((offset=left-p.scrollLeft)<0 || (offset=left+width-p.scrollLeft-client_width)>0))
        {   to_scroll.push({elem: p, prop: 'scrollLeft', from: p.scrollLeft, offset: offset});
        }
        if (client_height<p.scrollHeight-1 && ((offset=top-p.scrollTop)<0 || (offset=top+height-p.scrollTop-client_height)>0))
        {   to_scroll.push({elem: p, prop: 'scrollTop', from: p.scrollTop, offset: offset});
        }
        e = p;
        left += e.offsetLeft;
        top += e.offsetTop;
    }
    var x = 0;
    function apply()
    {   x = Math.min(x+1/(DURATION * FPS), 1);
        for (var i=to_scroll.length-1; i>=0; i--)
        {   to_scroll[i].elem[to_scroll[i].prop] = to_scroll[i].from + to_scroll[i].offset*x*x;
        }
        if (x < 1)
        {   setTimeout(apply, 1000/FPS);
        }
    }
    apply();
}
于 2017-05-28T19:04:54.803 回答
2

只是补充一下,以防它帮助某人,

我正在开发适用于 iOS 和 Android 的 PWA,并且一直在使用该scrollIntoView()方法,直到我发现scrollIntoViewOptionsSafari 不支持该对象,因此无法平滑滚动或其他任何东西等。

对于带有纯 JS 的 iOS,我能够scrollIntoView通过平滑滚动和“最近”选项模仿 ......好吧,纯 TypeScript ......

单击处理程序或 w/e:

const element = *elementToScrollIntoView*;
const scrollLayer = *layerToDoTheScrolling*

if (/iPad|iPhone|iPod/.test(navigator.userAgent) {
    let position;
    const top = element.offsetTop - scrollLayer.scrollTop;
    if (element.offsetTop < scrollLayer.scrollTop) {
            // top of element is above top of view - scroll to top of element
        position = element.offsetTop;
    } else if (element.scrollHeight + top < scrollLayer.offsetHeight) {
            // element is in view - don't need to scroll
        return;
    } else if (element.scrollHeight > scrollLayer.offsetHeight) {
            // element is bigger than view - scroll to top of element
        position = element.offsetTop;
    } else {
            // element partially cut-off - scroll remainder into view
        const difference = scrollLayer.offsetHeight - (element.scrollHeight + top);
        position = scrollLayer.scrollTop - difference;
    }
        // custom function for iOS
    scrollToElement(scrollLayer, position, 200);
} else {
        // just use native function for Android
    element.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
}

手动滚动功能:

scrollToElement(scrollLayer, destination, duration) {
    if (duration <= 0) {
        return;
    }
    const difference = destination - scrollLayer.scrollTop;
    const perTick = (difference / duration) * 10;

    setTimeout(() => {
        scrollLayer.scrollTop = scrollLayer.scrollTop + perTick;
        if (scrollLayer.scrollTop === destination) {
            return;
        }
        scrollToElement(scrollLayer, destination, duration - 10);
    }, 10);
}

注意:处理程序中的大嵌套 if 和计算只是为了找到“最近”位置,因为我试图复制该行为,但只是使用 scrollToElement 函数动画滚动到顶部(没有选项对象的默认行为)你可以利用:

scrollToElement(scrollLayer, element.offsetTop, 200);
于 2019-04-08T11:05:13.110 回答
0

您可以尝试将 evt.preventDefault() 添加到函数中。这应该会覆盖正常的“点击链接”功能。例子:

    // Scroll to anchor ID using scrollTO event
function linkClicked(evt) { // function to listen for when a link is clicked
  evt.preventDefault();
  evt.scrollIntoView({behavior: 'smooth'});

}

// Scroll to section on link click
navBar.addEventListener('click', linkClicked);
于 2020-05-18T19:24:12.127 回答