如何获取CSS媒体查询以使用jQuery

如何获取CSS媒体查询以使用jQuery

本文介绍了如何获取CSS媒体查询以使用jQuery $(window).innerWidth()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我想让jQuery处理一个菜单,而CSS在调整浏览器大小时会对窗口背景做些事情。 :<$ p

  if($(window).innerWidth()< mediaQueries ['small']){
/ /(其中'small'将是966)
//在菜单上执行jQuery东西ul
}

而且CSS有这样的:

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

使用Firefox时,



由于其他浏览器可能对滚动条使用不同的宽度,因此,只是添加17px的CSS将不会真正解决这个问题。那么如何获取jQuery来考虑滚动条? $(window).innerWidth()似乎没有为我这样做。





打开此页在Firefox,Opera或IE中为孤立版本的问题。 (Chrome和Safari不会遇到这个问题。)因此:Webkit:+1,Gecko:-1,Trident:-1,Presto:-1。)

解决方案

除了JackieChiles的解决方案:



使用

 var width = Math.max )



这个解决方案是(IMHO) )更好,因为JS不依赖于任何CSS。



感谢JackieChiles和Arjen为这个解决方案!


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.)

解决方案

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!

这篇关于如何获取CSS媒体查询以使用jQuery $(window).innerWidth()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 16:06