【问题标题】:Can't hide fixed menu using media queries无法使用媒体查询隐藏固定菜单
【发布时间】:2016-06-20 21:26:47
【问题描述】:

我有一个水平菜单,当您滚动浏览它时,它会粘在网络浏览器的顶部。为了实现它,我正在使用 javascript (jquery)。现在我想隐藏该菜单并以特定分辨率显示移动菜单,但是当我给菜单类“显示:无”时,它只会隐藏原始菜单。
如果我将 .original 或 .menu 设置为“display:none”,它会隐藏原始静态菜单,并且固定菜单会立即贴在 Web 浏览器的顶部(您不必滚动)。
将 .cloned 设置为 "display:none" 没有任何作用。 如何摆脱固定菜单?

脚本:

<script>

        // Create a clone of the menu, right next to original.
$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();

scrollIntervalID = setInterval(stickIt, 10);


function stickIt() {

  var orgElementPos = $('.original').offset();
  orgElementTop = orgElementPos.top;               

  if ($(window).scrollTop() >= (orgElementTop)) {
    // scrolled past the original position; now only show the cloned, sticky element.

    // Cloned element should always have same left position and width as original element.     
    orgElement = $('.original');
    coordsOrgElement = orgElement.offset();
    leftOrgElement = coordsOrgElement.left;  
    widthOrgElement = orgElement.css('width');
    $('.cloned').css('left',leftOrgElement+'px').css('top',0).css('width',widthOrgElement).show();
    $('.original').css('visibility','hidden');
  } else {
    // not scrolled past the menu; only show the original menu.
    $('.cloned').hide();
    $('.original').css('visibility','visible');
  }
}

    </script>

CSS:

@media screen and (max-width:960px){
    .cloned {
        display: none;
    }

    .original {
        display: none;
    }

    .menu {
        display: none;
    }

    #navi {
        display: none;
    }

    #content {
        width: 90%;
    }
}


编辑:

jsfiddle: https://jsfiddle.net/765kadoj/3/

【问题讨论】:

  • 你可以创建jsfiddle或codepen来轻松调试吗?
  • 好的,给我几分钟
  • 我添加了 jsfiddle !

标签: javascript jquery css menu media-queries


【解决方案1】:

它发生的原因是因为您的 javascript 在设置后会覆盖您的 css。你有两个选择:

  1. 当屏幕小于960px 时,您需要编写一些javascript 将.cloned 类的css 更改为display: none

  2. 您可以使用!important 覆盖,如下所示:

    .cloned { display: none !important; }

但是,我强烈建议使用选项 1,因为 !important 覆盖通常不是最佳做法。有关!important 的更多信息,请参阅此article

【讨论】:

  • 从不建议使用重要的,OP 可以更具体地使用 CSS 选择器。
  • @dippas 正如我在帖子中所说,“我强烈建议使用选项 1。”我同意你的看法,这不应该是常见的做法(尤其是在这种特定情况下),但在某些情况下它更容易接受;例如,自定义用户样式表。我将选项 2 仅作为参考。但感谢您的意见
  • 有什么方法可以通过媒体查询触发 javascript 吗?我也可以 100% 确定,javascript 每次都会隐藏和显示 .cloned 菜单吗?
  • @kkamil4sz jsfiddle.net/765kadoj/7 你只需要额外的几行代码
猜你喜欢
  • 2020-07-31
  • 1970-01-01
  • 2021-12-18
  • 2013-05-08
  • 2014-05-21
  • 1970-01-01
  • 2014-08-14
  • 1970-01-01
  • 2014-05-10
相关资源
最近更新 更多