修正了两个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'); } });更多推荐
发布评论