繁体   English   中英

jQuery 滚动顶部动画

[英]jQuery scrollTop animate

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

Use CSS transitions and animation whenever possible which is more smooth compared to jquery animations, this can be done using css transition check the below code. 此外,如果浏览器将页面滚动到缓存中的某个部分,您需要在页面加载时触发滚动。

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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM