繁体   English   中英

位置固定,但滚动<body>

[英]Position fixed, but scroll on <body>

我有这种情况:

  • 我正在创建的网站有一个左侧边栏,必须设置为高度100%,同时滚动网页,其中的内容肯定超过1000px高度。
  • 因为内容的高度,我在这个侧边栏元素上得到垂直滚动,当我的内容有足够的内容时,我得到另一个滚动条。

我要做的是以某种方式转移,从“固定”元素滚动到主页面滚动...

我希望你能理解我......

我希望这个截图,也可以帮助你理解我的要求:

链接

提前谢谢你的答案。

你的问题让我感兴趣,所以我试了一下。

您可以将侧边栏设置为:

#sidebar{
    position:fixed;
    min-height:100%;
    top:0;
    left:0;
    /* ... */
}

现在,为了使其滚动,我们可以使用其margin-top css属性:

  • 如果我们向下滚动,除非我们滚动超过它的高度,否则我们减少它。
  • 如果我们向上滚动,我们会增加它,除非它高于零。

我创建了一个包含2个函数的ScrollingSidebar类来处理:

// ScrollingSidebar class
// Define some variables and bind events
function ScrollingSidebar(el){
    this.sidebar = el;
    var that = this;
    that.updateVariables();
    document.addEventListener('scroll',function(){that.scrollSidebar();});
    window.addEventListener('resize',function(){that.updateVariables();});
}

// Updates variables used for calculation
ScrollingSidebar.prototype.updateVariables = function(){
    this.height = parseInt( getComputedStyle(this.sidebar).height );
    document.body.style.minHeight = this.height + 'px';
    this.winHeight = parseInt( window.innerHeight );
    this.previousScrollPos = Math.floor( document.body.scrollTop ||
                                   document.documentElement.scrollTop ||
                                   document.body.parentNode.scrollTop
                                 );
    this.scrollSidebar();
};

// Updates the sidebar's margin-top
ScrollingSidebar.prototype.scrollSidebar = function(){
    var curScrollPos = Math.floor( document.body.scrollTop ||
                                   document.documentElement.scrollTop ||
                                   document.body.parentNode.scrollTop
                                 );
    if(this.previousScrollPos < curScrollPos){
        this.sidebar.style.marginTop =  - Math.min(-parseInt( getComputedStyle(this.sidebar).marginTop ) + (curScrollPos - this.previousScrollPos),
                                                  this.height-this.winHeight) + 'px';
    } else {
        this.sidebar.style.marginTop = Math.min(0,parseInt( getComputedStyle(this.sidebar).marginTop ) + this.previousScrollPos-curScrollPos) + 'px';
    }
    this.previousScrollPos = curScrollPos;
};

您可以像这样使用它:

// Create an instance of ScrollingSidebar
var sidebar = document.getElementById('sidebar');
var x = new ScrollingSidebar(sidebar);

JS小提琴演示(含少量内容)

JS小提琴演示(内容很多)

注意: 我没有花时间很好地评论我的代码,但如果您对此有任何疑问或任何问题,请随时提出。

如果您的网站是响应式的,并且您不希望在小屏幕上使用此方法,则可能需要考虑使用条件来禁用它。

暂无
暂无

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

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