繁体   English   中英

滚动时如何制作视差侧边栏

[英]How to make parallax sidebar when scrolling

我得到了一些带有大侧边栏和小内容的布局。 “固定部分”是指粘性位置。

布局示例

我试着用scrollTop做这个,但是侧边栏就是这样做的

有些麻烦

代码必须仅在主要内容高度小于侧边栏内容时执行。

最后一次尝试的代码。

function sidebarParallax(expertStatisticsHeight) {
        var sidebar = $('aside.site-aside');
        var main = $('main.site-content');
        var footer = $('footer');
        var c = 1;

        sidebar.css({
            position: 'absolute',
            right: 0,
            width: $(document).width() - main.width(),
        });

        if ((expertStatisticsHeight + $banner.height()) > main.height()) {
            var speed = c - (main.height() / sidebar.height());

            sidebar.css('transform', 'translateY(' + -speed + 'px)');
        } else {
            sidebar.removeAttr('style');
        }
    }

如何制作,当我在底部滚动,侧边栏底部和内容底部变得相同。

先感谢您!

我找到了解决方案!

var sidebar = $('aside.site-aside');
var main = $('main.site-content');
var banners = $('.section-banner');
var bannersCount = banners.length;
var isMainLessThanSidebar = init();

$(window).resize(checkSize);

$(document).ajaxComplete(checkSize);

$(window).scroll(function() {
    if (isMainLessThanSidebar) {
        return sidebarParallax();
    }
});

function checkSize() {
    isMainLessThanSidebar = init();
}

function sidebarParallax() {
    var scrolled = window.pageYOffset || document.documentElement.scrollTop;
    var scrollLeft = mainDiff - scrolled;
    var percent = scrollLeft / mainDiff;
    sidebar.css('top', -diff + (diff * percent));
}

function init() {
    sidebar.css({
        position: 'absolute',
        right: 0,
        width: $(document).width() - main.width()
    });

    var isMainLess = sidebar.height() > main.height();

    if (isMainLess) {
        diff = sidebar.height() - main.height();
        mainDiff = $('main.site-content').height() - document.documentElement.clientHeight;
        sidebarParallax();
    } else {
        sidebar.removeAttr('style');
    }

    return isMainLess;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM