Triggering jquery with css media queries

大城市里の小女人 提交于 2019-11-27 01:38:15

The Modernizr library supports making direct JavaScript calls that evaluate media queries.

If you don't want to do that, you could have your different CSS rules drive some property of a hidden element, and you could then use ".css()" to check the value from jQuery. In other words, the rule for "bigger than 1000px wide" could set a hidden <div> to "width: 1000px", and you could then check

if ( $("#widthIndicator").css("width") === "1000px") {
  // whatever

Here is a dumb jsfiddle demonstrating. Drag the middle separator bar left and right to see that the JavaScript code (in the interval timer) detects the change to effective "width" of the hidden element.

If you refer to a responsive design then you could also trigger an existing element's property without adding markup to your html,for example

if ( $("#navigation li").css("float") === "none") {

Using Modernizr, as Pointy pointed out, is pretty easy.

Add the following javascript:

$(document).ready(function() {
    function doneResizing() {
        if(Modernizr.mq('screen and (min-width:768px)')) {
            // action for screen widths including and above 768 pixels 
        }
        else if(Modernizr.mq('screen and (max-width:767px)')) {
            // action for screen widths below 768 pixels 
        }
    }

    var id;
    $(window).resize(function() {
        clearTimeout(id);
        id = setTimeout(doneResizing, 0);
    });

    doneResizing();
});

That way the Modernizr Mediaquery detection is run ALSO when you resize the browser window - not only when the document gets loaded initially!

I had a similar problem with some carousels that must be created on mobile, but destroyed in desktop... and I did not liked the solution of being checking window width in pixels, so I created a small function to "listen" when the mediaquery state changes, without the need of Modernizr.

You can define your own code in every state ("on entering mobile resolution", "on leaving desktop")... and there put your code.

Hope could be useful for someone else ;)
https://github.com/carloscabo/MQBE
(improvements and ideas are welcome ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!