jQuery scrollTop动画

时间:2020-08-02 11:36:56

标签: javascript jquery

css

.head { 
  width: 100%;
  left: 0px;
  top: 0px;
  height: 76px;
  border-bottom: 1px solid #e6e6e6;
  position: fixed;
  display: flex;
  background: #fff;
  z-index: 10;
 }

JavaScript

$(window).scroll(function () {
  const height = $(document).scrollTop();
  console.log(height);
  if (height > 0) {
    console.log("no 0");
    $("#tt-body-index .head").animate(
      {
        marginTop: 0,
      },
      1000,
      "swing"
    );
  } else if (height === 0) {
    console.log("0");
    $("#tt-body-index .head").animate(
      {
        marginTop: -76,
      },
      1000,
      "swing"
    );
  }
});

我正在使用jQuery编写脚本。 滚动开始时,.head出现并尝试使scrollTop 0消失。 .head出现是好的,但是当scrollTop为零时,它不会变成marginTop: -76

1 个答案:

答案 0 :(得分:0)

尽可能使用CSS过渡和动画,与jquery动画相比,它更平滑,这可以通过使用CSS过渡检查以下代码来完成。另外,如果浏览器将页面滚动到缓存中的某个部分,则需要触发页面加载滚动。

CSS

.head { 
    width: 100%;
    left: 0px;
    top: -80px;
    height: 76px;
    border-bottom: 1px solid #e6e6e6;
    position: fixed;
    display: flex;
    background: #fff;
    z-index: 10;
    background-color: aqua;
    transition: top 1s;
}
body.showHeader .head{
    top: 0px;
}

JavaScript

$(window).scroll(function () {
    const height = $(document).scrollTop();
    console.log(height);
    if (height < 76) {                    
        $('body').removeClass('showHeader')
    } else  {
        $('body').addClass('showHeader')
    }
}).scroll();