获得平滑且有点延迟的滚动

时间:2017-04-11 07:10:52

标签: javascript html css scroll

如何使用鼠标滚轮获得漂亮流畅的滚动?我没有兴趣点击一个链接,页面自动向下滚动,它应该是鼠标滚轮。

一个例子是adidas微型网站: http://www.adidas.dk/climazone

如果这是解决方案,Javascript就可以了

2 个答案:

答案 0 :(得分:2)

您可以使用jQuery鼠标滚轮插件,您可以在此处获取最新版本https://github.com/jquery/jquery-mousewheel

然后在你的js文件中你可以这样做:

$('body').on('mousewheel', debouncer(function (event, deltaY, deltaX) {

    if (deltaY < 1) {
        nextSlide();
    }
    else {
        prevSlide();
    }
}));

你需要定义nextSlide()&amp; prevSlide()根据您的网站结构显示鼠标滚轮发生的不同部分。

我在我自己的网站上使用过这种方法,也许它可以帮到你:

function nextSlide() {
if ($('.starter-template.active').hasClass('prevlast')||$('.starter-template.active').hasClass('last')) {
    $('.footer').fadeOut();
} else {
    $('.footer').fadeIn();
}

if ($('.starter-template.active').hasClass('last')) {
    return false
}
else {
    $('.starter-template.active').removeClass('active').addClass('up').fadeOut().next('.starter-template').fadeIn().addClass('active');
}
}
function prevSlide() {
if ($('.starter-template.active').hasClass('last')) {
    $('.footer').fadeIn();
}
if ($('.starter-template.active').hasClass('first')) {
    return false
}
else {
    $('.starter-template.active').removeClass('active').removeClass('up').prev('.starter-template').fadeIn().addClass('active');
 }
}

答案 1 :(得分:1)

纯粹和轻松的JS:
您需要一个position:fixed的容器,其父级高度由javascript定义。然后使用调用requestAnimationFrame的js脚本,在JS中使用transform:translate3d(x,x,x)更改容器属性Math.round(),以便延迟翻译。

这是我使用该方法制作的JSFiddle,可以帮助您:https://jsfiddle.net/nesquimo/0cwutgyx/3/

var container = document.getElementById('YOUR CONTAINER');
var bodyScrollLevel = 0, newY, destY, currentY, windowScrollTop;
smoothScrollMove = function () {
    requestAnimationFrame(smoothScrollMove);
    windowScrollTop = window.pageYOffset;
    destY = windowScrollTop;
    currentY = -bodyScrollLevel;
    if (Math.round(currentY) != Math.round(destY)) {
       newY = Math.round(currentY + ((destY - currentY) * 0.08));
       bodyScrollLevel = -newY;
       container.style.transform = "translate3d(0,-" + newY + "px, 0)";
    }
}
requestAnimationFrame(smoothScrollMove);