原生JS实现平滑到指定位置(仿锚点效果)

点击按钮,页面滑动到指定位置,仿a标签锚点效果

function goTarget(target) {
    var timer = null;
    var lastPos = 0;
    function goMove() {
        var currentPosition = document.documentElement.scrollTop || document.body.scrollTop;
        currentPosition = parseInt(currentPosition)
        if(lastPos == currentPosition) { //页面高度不够长,未滑动到指定位置的时候,已经滑动到底部了
            window.scrollTo(0, target);
            clearInterval(timer);
            console.log('move to ' + target);
            return;
        }
        lastPos = currentPosition;
        console.log(target, currentPosition);
        if(Math.abs(currentPosition - target) < 20) {
            window.scrollTo(0, target);
            clearInterval(timer);
            console.log('move end');
            return;
        }
        if (currentPosition -target > 20) {
            currentPosition -= 20;
            window.scrollTo(0, currentPosition);
        } else {
            currentPosition += 20;
            window.scrollTo(0, currentPosition);
        }
    }
    timer = setInterval(goMove, 10);
}
$('#s-list1').on('click', function () {
    var targetPos = parseInt($('#s-manCpOne').offset().top);
    goTarget(targetPos);
})
转载
原文:https://blog.csdn.net/u012193330/article/details/82910811 



相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页