简体   繁体   English

如何制作仅用于水平滚动的粘性导航栏?

[英]How to make sticky navigation bar only for horizontal scrolling?

I have a huge table that goes out of screen and I have horizontal and vertical scroll.我有一个超出屏幕的巨大表格,并且有水平和垂直滚动。 Now, my problem is that I want to make sticky navbar which stays on top only on horizontal scroll and hides when I scroll down... and again shows when I scroll on top of page.现在,我的问题是我想制作粘性导航栏,它只在水平滚动时保持在顶部,当我向下滚动时隐藏......当我滚动到页面顶部时再次显示。

I tried this solution with css and js, but navbar hides also when I scoll horizontally.我用 css 和 js 尝试了这个解决方案,但是当我水平滑动时,导航栏也会隐藏。 It should be hidden only on vertical scroll它应该只在垂直滚动时隐藏

    <style>
        #sticky {
            position: fixed;
            top: 0;
            width: 100%;
        }
    </style>

    <script>
        var prevScrollpos = window.pageYOffset;
        window.onscroll = function() {
            var currentScrollPos = window.pageYOffset;
            if (prevScrollpos > currentScrollPos) {
                document.getElementById("sticky").style.top = "0";
            } else {
                document.getElementById("sticky").style.top = "-70px";
            }
            prevScrollpos = currentScrollPos;
        }
    </script>

It is possible to use overflow-x: scroll to have horizontal scroll bar:可以使用overflow-x: scroll来获得水平滚动条:

#sticky {
      height: 60px;
      display: table-row;
      background: #333;
      position: fixed;
      right: 0;
      left: 0;
      overflow-x: scroll;
}

UPDATE:更新:

Sure, you can add style via JavaScript:当然,您可以通过 JavaScript 添加样式:

document.getElementById('sticky').style.overflowX = 'scroll';

You have to use position sticky which works like a toggle between fixed and relative based on your scroll position您必须使用 position 粘性,它的工作原理就像根据您的滚动 position 在固定和相对之间切换

 body { margin: 0; font-size: 28px; font-family: Arial, Helvetica, sans-serif; width:200vw; height:300vh; }.header { background-color: #f1f1f1; padding: 30px; text-align: center; } #navbar { overflow: hidden; background-color: #333; width: 100vw; left: 0; position: sticky; } #navbar a { float: left; display: block; color: #f2f2f2; text-align: center; padding: 14px 16px; text-decoration: none; font-size: 17px; } #navbar a:hover { background-color: #ddd; color: black; } #navbar a.active { background-color: #4CAF50; color: white; }
 <,DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width. initial-scale=1"> </head> <body> <div class="header"> <h2>Scroll Down</h2> <p>Scroll down to see the sticky effect:</p> </div> <div id="navbar"> <a class="active" href="javascript:void(0)">Home</a> <a href="javascript:void(0)">News</a> <a href="javascript:void(0)">Contact</a> </div> </body> </html>

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

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