修正了两个div元素之间的div(Fixed div between two div elements)

编程入门 行业动态 更新时间:2024-10-08 02:21:15
修正了两个div元素之间的div(Fixed div between two div elements)

当滚动位置在两个div元素之间时,我尝试创建一个固定的div元素。 我使用这段代码来创建固定的元素:

var sidebar = $('.sidebar').offset().top; $(window).scroll(function() { if ($(window).scrollTop() > sidebar) { $('.sidebar').addClass('fixed'); }else{ $('.sidebar').removeClass('fixed'); } });

当蓝色div达到时,我不知道如何去除固定类。 我尝试获取蓝色div的当前位置并将其添加到if语句中: var blueDiv = $('.bottom').offset().top :

if ($(window).scrollTop() > sidebar && $(window).scrollTop() < blueDiv ){ // add fixed class }else{ // remove fixed class }

小提琴: https : //jsfiddle.net/L7p5yeet/

I try to create a fixed div element when the scroll position is between two div elements. I use this code to create the fixed element:

var sidebar = $('.sidebar').offset().top; $(window).scroll(function() { if ($(window).scrollTop() > sidebar) { $('.sidebar').addClass('fixed'); }else{ $('.sidebar').removeClass('fixed'); } });

I don't know how to remove the fixed class when the blue div reached. I tried to get the current position of the blue div and add it to the if statement: var blueDiv = $('.bottom').offset().top:

if ($(window).scrollTop() > sidebar && $(window).scrollTop() < blueDiv ){ // add fixed class }else{ // remove fixed class }

Fiddle: https://jsfiddle.net/L7p5yeet/

最满意答案

您在检查侧边栏是否已达到蓝色div时忘记了包含边栏的高度:

var sidebar = $('.sidebar').position().top; var blueDiv = $('.bottom').position().top - $('.sidebar').innerHeight(); $(window).scroll(function() { var sT = $(window).scrollTop(); if (sT > sidebar && sT < blueDiv) { $('.sidebar').addClass('fixed'); }else{ $('.sidebar').removeClass('fixed'); } });

You forgot to include the height of the sidebar when you checked if the sidebar already reached the blue div:

var sidebar = $('.sidebar').position().top; var blueDiv = $('.bottom').position().top - $('.sidebar').innerHeight(); $(window).scroll(function() { var sT = $(window).scrollTop(); if (sT > sidebar && sT < blueDiv) { $('.sidebar').addClass('fixed'); }else{ $('.sidebar').removeClass('fixed'); } });

更多推荐

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

发布评论

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

>www.elefans.com

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