【问题标题】:Show/Hide Element on Scroll for certain width, toggle for other width在特定宽度的滚动上显示/隐藏元素,切换到其他宽度
【发布时间】:2015-07-24 20:58:52
【问题描述】:

我正在尝试制作一个在向下滚动时隐藏并在向上滚动时重新出现的导航,除非窗口宽度小于 775。如果宽度小于 775,则行为应该是导航栏的切换它在滚动时保持固定位置。

我整理了一个codepen here 来展示我遇到的问题。如果页面加载时窗口 > 775,它可以正常工作,如果窗口

现在,我意识到人们在使用我的网站时可能不会一直调整大小,但这让我发疯了。肯定有办法让我的蛋糕也吃吗?

我尝试了不同的条件语句来检查显示的 css 值、比较窗口宽度以及使用 jQuery 选择器 :visible。一切的结果都是一样的。谁能帮我?基本上我想要的是如果 #hamburger 正在显示(显示:块),则切换应该生效。如果#hamburger被发送到display: none,淡入/淡出应该是有效的。

这是我现在的位置:

//toggle hamburger icon + menu on mobile
$('#hamburger').click(function() {
    $('nav').toggle();  
});

//hide/show nav on scroll
function hideNav() {    
    var lastScrollTop = 0; 
    $(window).scroll(function(event){
        var st = $(this).scrollTop();
        if (st > lastScrollTop)
            $('nav').fadeOut();  
        else 
            $('nav').fadeIn();
        lastScrollTop = st;
    });
}

//check window size on load
var windowWidth = $(window).width();
if (windowWidth > 775)
    hideNav();

//adjust if the window is resized
function resizeWindow(){
    var newWindowWidth = $(window).width();
    if (newWindowWidth > 775)
        hideNav();           
    else if (newWindowWidth <= 775)
        $('nav').hide();
 }

 $(window).resize(resizeWindow);   

【问题讨论】:

    标签: jquery html css responsive-design toggle


    【解决方案1】:

    试试这个:

    $('#hamburger').click(function() {
      $('nav').toggle();
    });
    
    function hideNav() {
      var lastScrollTop = 0;
      $(window).on('scroll', function(event) {
        var st = $(this).scrollTop();
        if (st > lastScrollTop) {
          $('nav').fadeOut();
        } else {
          $('nav').fadeIn();
        }
        lastScrollTop = st;
    
      });
    }
    
    //check window size
    var windowWidth = $(window).width();
    
    if (windowWidth > 775) {
      hideNav();
    }
    
    //adjust the nav functionality if the window is resized
    
    function resizeWindow() {
      $(window).off('scroll'); // unbind scroll event
    
      windowWidth = $(window).width(); // you may as well re-use windowWidth as it's global
      console.log(windowWidth);
      if (windowWidth > 775) {
        $('nav').show();
        hideNav();
      } else if (windowWidth <= 775) {
        $('nav').hide();
      }
    }
    
    $(window).resize(resizeWindow);
    

    Updated Pen

    【讨论】:

    • 是的!谢谢皮特。更新脚本中的 cmets 帮助我学习了一些新东西。真的很感激。
    • @Pete 我试图解决同样的问题!非常感谢您的回答!效果很好!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-03
    • 2015-09-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-08
    相关资源
    最近更新 更多