在滚动时固定/取消固定Div [英] Fixing / Unfixing Div when scrolling

查看:161
本文介绍了在滚动时固定/取消固定Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我有4个div(横幅,左侧内容,正确的内容和页脚)。横幅和左侧内容div是固定的,而右侧内容和页脚不是。我想要发生的是当页脚顶部遇到左侧内容div的底部时,它会解除自身并与右侧div一起滚动。

Basically i have 4 divs (a Banner, left content, right content, and a footer). The banner and left content divs are fixed while the right content and footer are not. What I'd like to have happen is when the top of the footer meets the bottom of the left content div have it unfix itself and scroll together with the right div.

我在下面的jsfiddle中设置了一个预览。

I setup a preview of what i currently have in jsfiddle below.

http://jsfiddle.net/sgcer/270/

<div id="banner">BANNER</div>
<div id="content">
    <div id="left">LEFT</div>
    <div id="right">RIGHT</div>
</div>
<div id="footer">FOOTER</div>

#banner {
    float: left;
    width: 100%;
    height: 100px;
    background-color: #00ff00;
    position: fixed;
}
#content {
    height: auto;
}
#left {
    float: left;
    width: 30%;
    height: 600px;
    background-color: #ccc;
    position: fixed;
    margin-top: 100px;
}
#right {
    float: right;
    width: 70%;
    height: 750px;
    background-color: #333;
    margin-top: 100px;
}
#footer {
    clear: both;
    width: 100%;
    height: 100px;
    background-color: #ff0000;
}

任何帮助将非常感激!

推荐答案

我叉开了小提琴: http:// jsfiddle .net / YK72r / 2 /

我在每个滚动事件上调用了 if ,使用一点指标数学来找到所需的高度,使用jQuery的 css 方法更改左侧边栏的CSS,然后添加一个 else 语句以在向后滚动时还原它。

What I did is called an if on every scroll event, used a bit of metrics math to find the height needed, changed the css of the left sidebar using jQuery's css method, and then added an else statement to revert it when scrolling back up.

var scrollHeight;

$(window).ready(function() {
    scrollHeight = $('#footer').offset().top - $('#left').height() - $('#left').offset().top;
});

$(window).scroll(function() {
    if ($(document).scrollTop() >= scrollHeight) {
        $('#left').css({
            'position': 'relative',
            'margin-top': '350px'
        });
    } else {
        $('#left').css({
            'position': 'fixed',
            'margin-top': '100px'
        });
    }
});

请注意,我改变了高度一点,所以记住css像素值。

Note that I changed the heights a bit, so mind the css pixel values.

这篇关于在滚动时固定/取消固定Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆