javascript - 创建两个不同的标题——粘性/滚动和顶部

标签 javascript jquery html css

使用我当前的代码,当页面加载时,白色条形标题位于顶部。当你滚动时,它会消失,当你滚动到顶部时,白色标题又回来了。所以我取得了一些进步。 我想要得到的是当滚动条在顶部时有一个透明的标题:(https://i.imgur.com/5DiVZpp.png)

对于主要的白色栏标题,要保持粘性并一直向下,如下所示:( https://i.imgur.com/lhlGsW6.png ) 当您向上滚动时,它会淡出透明标题。

CSS:

#header{position:fixed;
       left:0;top:0;right:0;height:106px;z-index:100;
    -webkit-transition:background-color 0.2s ease-in-out;
        -moz-transition:background-color 0.2s ease-in-out;
        -ms-transition:background-color 0.2s ease-in-out;
        -o-transition:background-color 0.2s ease-in-out;
        transition:background-color 0.2s ease-in-out
}
#header .logo{position:absolute;left:0;top:0;width:162px;height:106px}
#header .logo a{display:block;position:absolute;left:50%;top:50%;
                margin:-30px 0 0 -60px;width:120px;height:60px;
                text-indent:-99999px;
                background-image:url("header_logo.png")}
#header.scroll{border-bottom:1px solid #ededed;background:#fff;} /* so this is the transparent header?
#header.scroll .logo a{background-image:url("header_logo_transp.png")}

Javascript:

$(window).scroll(function () {
   var sc = $(window).scrollTop()
   if (sc == 0) {
   $("#header").addClass("scroll");
   //document.removeElementbyId(header); when I put this line in, the header wasn't there when the page first loads up-- kind of what I want, but I want the secondary header to be up there when sc==0
   } 
   else {
   $("#header").removeClass("scroll");

    }
});

HTML:

<div id="header" class="scroll" style="top: 0px;">
        <h1 class="logo"><a href="#">WEBSITE</a></h1>
        <a href="#" title="Menu" class="btn_menu"></a>

最佳答案

您遇到的问题可能是由于“滚动”的性质造成的。它不会获取每个像素值。稍微更改您的 if 语句以包含 1 作为检查将有助于确保在应有的时候添加和删除类。

示例:https://codepen.io/SROwl/pen/Mdbwpy

HTML:

<div class="container">
  <div class="nav top">Nav Top</div>
</div>

SCSS:

body {
  background: #000;
  padding: 0;
  margin: 0;
}
.container {
  height: 4000px;
}
.nav {
  background: lightgray;
  padding: 15px;
  height: 50px;
  width: 100%;
  border: 1px solid gray;
  transition:  250ms ease;
  &.top {
    color: #fff;
    background: transparent;
  }
  &.fixed {
    position: fixed;
    background: #fff;
  }
}

jQuery:

$(window).on('scroll', function(){
var  winTop = $(window).scrollTop(),
  if (winTop >= 1) {    
    $('.nav').addClass('fixed').removeClass('top');
  } else if (winTop <= 0) {    
    $('.nav').addClass('top').removeClass('fixed');    
  }
})

关于javascript - 创建两个不同的标题——粘性/滚动和顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56121489/

相关文章:

javascript - 使用 Backbone 和 Node 将模型保存到服务器

javascript - 有没有办法让函数在完成后立即采取行动?

javascript - Canvas 上的 keyCode 事件上的多个键 - JS

javascript - 使用按钮在可见和隐藏之间切换

javascript - 将段落分成跨度

css - 滑动门技术 - 浏览器兼容性

JavascriptCore:在 JSExport 中将 javascript 函数作为参数传递

jquery - 表格粘列滚动错误 Chrome

javascript - 是否存在结合创建 html 元素和附加到目标的方法?

jQuery - 在 Div2 单击时显示 Div1,然后在单击文档时隐藏 Div1