javascript - 使 jQuery .show() 根据媒体查询分配显示

标签 javascript jquery css

根据 jQuery 文档,.hide() 效果存储元素的显示值,以便在调用 .show() 时恢复它。

The matched elements will be hidden immediately, with no animation. This is roughly equivalent to calling .css( "display", "none" ), except that the value of the display property is saved in jQuery's data cache so that display can later be restored to its initial value. If an element has a display value of inline and is hidden then shown, it will once again be displayed inline.

但是,我有一个导航 UL 元素,当屏幕宽度大于 768 时,它是 display:flex;,当屏幕宽度达到 768 时,它是 display:block;。所以如果你在 iPad 上垂直打开和关闭导航然后旋转到水平位置,应该是 display:flex; 的导航现在是 display:block;

顺便说一句,我正在使用 jquery.slimmenu.js来自@adnantopal。我试图通过添加 .css('display:flex'); 来覆盖它,具体取决于 $(window).width() 但 Slimmenu 的命令占上风。

最佳答案

Javascript:

CSS @media queries 的 javascript 等价物是 window.matchMedia:

var minWidth768px = window.matchMedia("(min-width:768px)");

if (minWidth768px.matches) {
    ....CODE HERE...
    }

jQuery:

最接近的 jQuery 等价物是 $(window).width()

但是... 您需要注意 $(window).width() 本身包括宽度窗口右侧的滚动条。

所以你需要做这样的事情:

$('body, html').css('overflow', 'hidden');
var windowWidth = $(window).width();
$('body, html').css('overflow', 'auto');

然后你可以在 jQuery 中继续:

if (windowWidth > 767)  {
        ....CODE HERE...
        }

关于javascript - 使 jQuery .show() 根据媒体查询分配显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41005327/

相关文章:

javascript - 如何在 dojo 或 JavaScript 中检查多个 undefined?

javascript - 奇怪的日期格式帮助

javascript - Jquery cycle - 具有不同速度转换的幻灯片?

jquery - 在 Fabric JS 中取消选择对象

javascript - 你能告诉我如何将图像和文本添加到我的 html 幻灯片吗?

jquery - 输入文本在窗口 10 上与 jquery 和 css 对齐

html - div 元素更改父 div 的位置(边距)

javascript - javascript 函数返回的语法(空格)会影响结果吗?

Javascript - React 解构数组

jquery - 页面滚动时标题下方的 div 的固定位置