位置固定,但滚动

时间:2015-02-22 22:42:13

标签: javascript jquery html css

我遇到这种情况:

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

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

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

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

link

提前感谢您的回答。

1 个答案:

答案 0 :(得分:0)

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

您可以将侧边栏设置为:

#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 Fiddle Demo (with a small amount of content)

JS Fiddle Demo (with a lot of content)

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

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