如何让 CSS 媒体查询与 jQuery $(window).innerWidth() 一起使用?

发布于 2024-12-20 15:49:29 字数 816 浏览 3 评论 0原文

我试图让 jQuery 处理菜单,而 CSS 在调整浏览器大小时对窗口背景做一些事情。

所以 jQuery 做了这样的事情:

if ( $(window).innerWidth() < mediaQueries['small']) {
    // (where 'small' would be 966)
    // Perform jQuery stuff on a menu ul
}

CSS 也有这样的事情:

@media all and (max-width: 966px) {
    body {
        background: url(smallback.jpg) no-repeat 0 0;
    }
}

当使用 Firefox 时,有一个 17 像素的间隙(这似乎是垂直滚动条宽度),其中 jQuery 的东西已经被处理了,但 CSS 还没有。

由于其他浏览器的滚动条可能使用不同的宽度,因此仅在 CSS 中添加 17px 并不能真正解决问题。那么如何让 jQuery 考虑滚动条呢? $(window).innerWidth() 似乎不适合我。

任何帮助将不胜感激。

在 Firefox、Opera 或 IE 中打开此页面以获取问题的独立版本。 (Chrome 和 Safari 不会遇到这个问题。到目前为止:Webkit:+1,Gecko:-1,Trident:-1,Presto:-1。)

I'm trying to let jQuery take care of a menu, while CSS does something to the window background when resizing the browser.

So jQuery does something like this:

if ( $(window).innerWidth() < mediaQueries['small']) {
    // (where 'small' would be 966)
    // Perform jQuery stuff on a menu ul
}

And CSS has something like this:

@media all and (max-width: 966px) {
    body {
        background: url(smallback.jpg) no-repeat 0 0;
    }
}

When using Firefox, there's a gap of 17 pixels (which seems to be the vertical scrollbar width) in which the jQuery stuff is already handled, but the CSS is not.

As other browsers may use different widths for their scrollbars, just adding 17px to the CSS won't really fix the problem. So how do I get jQuery to take the scrollbars into account? $(window).innerWidth() doesn't seem to do that for me.

Any help would greatly be appreciated.

Open this page in Firefox, Opera or IE for an isolated version of the problem. (Chrome and Safari don't suffer from this problem. Thusfar: Webkit: +1, Gecko: -1, Trident: -1, Presto: -1.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

小女人ら 2024-12-27 15:49:29

除了JackieChiles的解决方案:

使用

var width = Math.max( $(window).width(), window.innerWidth);

will always get you the width without scrollbars in any browser.

这个解决方案(恕我直言)更好,因为 JS 不依赖于任何 CSS。

感谢 JackieChiles 和 Arjen 提供的解决方案!

In addition to the solution of JackieChiles:

Using

var width = Math.max( $(window).width(), window.innerWidth);

will always get you the width without scrollbars in any browser.

This solution is (IMHO) better because the JS does not depend on any CSS.

Thanks to JackieChiles and Arjen for this solution!

瞄了个咪的 2024-12-27 15:49:29

我在与媒体查询完全相同的时间触发 JavaScript 的解决方案(即使面对设备或浏览器的怪癖,如此处所示)是触发我的 window.resize 逻辑以响应媒体查询的更改进行了查询。下面是一个示例:

CSS

    #my-div
    {
        width: 100px;
    }

    @media all and (max-width: 966px)
    {
        #my-div
        {
            width: 255px;
        }
    }

JavaScript

    var myDivWidth;

    $(document).ready(function() {
        myDivWidth = $('#myDiv').width();

        $(window).resize(function () {
            if ($('#myDiv').width() != myDivWidth) {
                //If the media query has been triggered
                myDivWidth = $('#myDiv').width();
                //Your resize logic here (the jQuery menu stuff in your case)
            }
        });
    });

在此示例中,每当 #myDiv 更改大小(触发媒体查询时会发生)时,您的 jQuery调整大小逻辑也将运行。

为简单起见,我使用了元素宽度,但您可以轻松使用要更改的任何属性,例如 body 背景。

这种方法的另一个优点是它使 window.resize 函数尽可能轻量级,这总是好的,因为每次窗口大小改变一个像素时都会调用它(在大多数现代浏览器中)反正)。

正如您所说,您遇到的错误在我看来是浏览器特定的问题。尽管直观上看起来不正确,但 Firefox(以及其他有问题的浏览器)实际上似乎符合 W3C 建议比 Webkit 浏览器更适合媒体查询。该建议指出视口宽度包括滚动条,而 JavaScript 窗口宽度似乎不包括滚动条,因此存在差异。

My solution to triggering JavaScript at the exact same time as media queries (even in the face of device or browser quirks as seen here) is to trigger my window.resize logic in response to a change that the media query made. Here's an example:

CSS

    #my-div
    {
        width: 100px;
    }

    @media all and (max-width: 966px)
    {
        #my-div
        {
            width: 255px;
        }
    }

JavaScript

    var myDivWidth;

    $(document).ready(function() {
        myDivWidth = $('#myDiv').width();

        $(window).resize(function () {
            if ($('#myDiv').width() != myDivWidth) {
                //If the media query has been triggered
                myDivWidth = $('#myDiv').width();
                //Your resize logic here (the jQuery menu stuff in your case)
            }
        });
    });

In this example, whenever #myDiv changes size (which will occur when the media query is triggered), your jQuery resize logic will also be run.

For simplicity I used an element width, but you could easily use whatever property you are changing, such as the body background.

Another advantage of this approach is that it keeps the window.resize function as lightweight as possible, which is always good because it is called every single time the window size changes by a single pixel (in most modern browsers anyway).

The bug that you encountered seems to me to be a browser-specific problem, as you said. Although it seems incorrect intuitively, Firefox (and other browsers with the issue) actually seems to match the W3C recommendation for media queries more closely than the Webkit browsers. The recommendation states that the viewport width includes scrollbars, and JavaScript window width does not seem to include scrollbars, hence the disrepancy.

木槿暧夏七纪年 2024-12-27 15:49:29

如果您碰巧使用 Modernizr,您可以包含媒体查询填充,它可以简化媒体查询检查

if (Modernizr.mq('all and (max-width: 966px)')) {
    ...
}

:与 CSS 相同:

@media all and (max-width: 966px) {
    ...
}

如果您无法使用 Modernizr 的 polyfill,请继续检查 Math.max(document.width, window.innerWidth)

If you happen to be using Modernizr, you can include the media query polyfill, which simplifies media query checks to:

if (Modernizr.mq('all and (max-width: 966px)')) {
    ...
}

Which is conveniently identical to your CSS:

@media all and (max-width: 966px) {
    ...
}

If you can't use Modernizr's polyfill, then stick with checking against Math.max(document.width, window.innerWidth).

森末i 2024-12-27 15:49:29

window.matchMedia 是一种触发事件的方式当媒体选择器启动或关闭时。它是新的,因此没有得到广泛支持,但似乎非常有用。

来自 MDN 的“使用代码中的媒体查询”

window.matchMedia is a way you can fire events when media selectors kick on or off. It's new so not widely supported, but seems pretty useful.

"Using media queries from code" from MDN

玻璃人 2024-12-27 15:49:29
var viewport = jQuery(window).innerWidth();

if( viewport > 979 )
{
  // your code here
}
var viewport = jQuery(window).innerWidth();

if( viewport > 979 )
{
  // your code here
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文