语句之间的元素抖动

时间:2019-01-05 08:09:11

标签: javascript jquery html css

如果您在蓝色框附近缓慢向下滚动(此刻将要执行第二条语句,我的意思是else语句)绿色框上有一个小故障和抖动,为什么会这样?

var target = $('.product-info-main').offset().top;

$(window).scroll(function() {
  var footer = $('.page-footer').offset().top;
  var element = $('.box-tocart').offset().top;
  
  var scrollTop = $(window).scrollTop();
  var windowHeight = $(window).height();
  if ((scrollTop >= target) && (scrollTop + windowHeight <= footer)) {
    $('.box-tocart').addClass('tobefix');
    //console.log('fixed');
  } else {
    $('.box-tocart').removeClass('tobefix');
    //console.log('not fixed');
  }

});
body {
    height: 2000px;
    margin: 0;
}

#nothing {
  height: 100px;
  background: red;
}

.product-info-main {
  height: 1000px;
}

.box-tocart {
  height: 30px;
  background: green;
  width: 100%;
}

.page-footer {
  background: blue;
  height: 100px;
}

.box-tocart.tobefix {
    position: fixed;
    bottom: 0;
    left: 0;
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="nothing"></div>
<div class="product-info-main">
  
</div>

<div class="box-tocart"></div>
<div class="page-footer"></div>

如何解决此问题?

1 个答案:

答案 0 :(得分:2)

为避免出现此问题,请定位:固定位置的固定元素将出现此问题。

  

粘性定位元素是其计算位置的元素   价值是粘性的。直到它被定位为相对位置   包含块超过了指定的阈值(例如将top设置为   在其流根(或其容器)中的值(不是auto)   在其中滚动),这时它被视为“卡住”,直到见面为止   其包含块的相对边缘。

source

var target = $('.product-info-main').offset().top;

$(window).scroll(function() {
  var footer = $('.page-footer').offset().top;
  var element = $('.box-tocart').offset().top;
  
  var scrollTop = $(window).scrollTop();
  var windowHeight = $(window).height();
  if ((scrollTop >= target) && (scrollTop + windowHeight <= footer)) {
    $('.box-tocart').addClass('tobefix');
    //console.log('fixed');
  } else {
    $('.box-tocart').removeClass('tobefix');
    //console.log('not fixed');
  }

});
body {
    height: 2000px;
    margin: 0;
}

#nothing {
  height: 100px;
  background: red;
}

.product-info-main {
  height: 1000px;
}

.box-tocart {
  height: 30px;
  background: green;
  width: 100%;
}

.page-footer {
  background: blue;
  height: 100px;
}

.box-tocart.tobefix {
    position: sticky;
    bottom: 0;
    left: 0;
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="nothing"></div>
<div class="product-info-main">
  
</div>

<div class="box-tocart"></div>
<div class="page-footer"></div>