在滚动时固定/取消固定Div

编程入门 行业动态 更新时间:2024-10-27 14:31:25
本文介绍了在滚动时固定/取消固定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.

jsfiddle/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 / 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

本文发布于:2023-10-08 03:10:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1471335.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Div

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!