在滚动 HTML/CSS 上的 header 上显示搜索栏

Display a Search bar on header on scroll HTML/CSS

我有一个搜索栏,它想在滚动时显示在 header 上,一个很好的例子就像这个网站上的那个:https://www.indiamart.com/

在同一个例子中,这个想法只是 show/hide 一旦用户使用内联 css display 属性 滚动页面,你可以做同样的事情或在至少提供一个代码示例,以便我们可以帮助您!

HTML

<div class="search-bar">
    <div class="sticky-search">
        Sticky Search: <input type="text" value="search" />
    </div>
</div>

CSS

.sticky-search {
    display:none;
    position:fixed;
    top:0px;
    left:0px;
    right:0px;
    background:blue;
    padding:10px;
}

JS

var searchHeight = $(".search-bar").outerHeight();
var offset = $(".search-bar").offset().top;
var totalHeight = searchHeight + offset;

console.log(totalHeight);
$(window).scroll(function(){
    if($(document).scrollTop() >= totalHeight) {
        $('.sticky-search').show();
    } else {
        $('.sticky-search').hide();
    }
});

方法 1 - 一种简单的方法是检测滚动并添加和删除包含 display: none;[= 的 class 19=]

你可以有一个事件监听器 -

window.addEventListener('scroll', function() {
   if( window.scrollY !== 0) {
            
      document.getElementById('searchBar').classList.add('scrolled');
   } else {
            
      document.getElementById('searchBar').classList.remove('scrolled');
   }
});

与CSS-

.noScroll
{
    background: yellow;
    position:fixed;
    height: 50px; /*Whatever you want*/
    width: 100%; /*Whatever you want*/
    top:0;
    left:0;
    display:none;
}

/*Use this class when you want your content to be shown after some scroll*/
.scrolled
{
  display: block !important;
}

.parent {
  /* something to ensure that the parent container is scrollable */
  height: 200vh;
}

而 html 将是 -

<div class="parent">
  <div class ='noScroll' id='searchBar'>Content you want to show on scroll</div>
</div>

这是相同的 JSFiddle - https://jsfiddle.net/kecnrh3g/

方法 2 - 另一种简单的方法是

<script>
let prevScrollpos = window.pageYOffset;
window.onscroll = function() {
let currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById('searchBar').style.top = '-50px';
  } else {
    document.getElementById('searchBar').style.top = '0';
  }
  prevScrollpos = currentScrollPos;
}
</script>

与 html -

<div class="parent">
  <div id ='searchBar'>Content you want to show on scroll</div>
</div>

和css

#searchBar {
  background: yellow;
  position: fixed;
  top: 0;
  left: 0;
  height: 50px;
  width: 100%;
  display: block;
  transition: top 0.3s;
}

.parent {
  height: 200vh;
}

这是相同的 JSFiddle - https://jsfiddle.net/0tkedcns/1/