jQuery media queries with match media

淺唱寂寞╮ 提交于 2019-12-11 03:16:31

问题


I am trying to change my jQuery code depending on screen resolutions. I am animating main content area, and would like to change it's width on different screen sizes.

After a lot of searching online i found something that might be helpful, but i can't get it to work.Here is the code snippet that needs to be changed. It is called Match Media, something like CSS3 media queries, only for JavaScript.

  var mq = window.matchMedia( "(max-width: 320px)" );
         if (mq.matches) {
           menuLink.click(function(){
            innerContent.css("display", "none");
            contentWrapper.stop().animate(
                    {width: '40em'},
                    {duration:1200,easing: 'easeOutBack'}
            );
            closeButton.stop().delay(800).animate({opacity:'1'},600,'easeInSine');
            $("#fadeBg").fadeIn();
         });
          }

The main thing that i want here is when the max-width criteria is fulfilled to animate the contentWrapper for 40 em. But it seems that nothing is happening.

Thanks in advance


回答1:


Are you doing this on document ready?

$( function(){
  ...
  var mq = window.matchMedia( "(max-width: 320px)" );

} );



回答2:


It worked with me when I added a listener to it.

  var mq = window.matchMedia( "(max-width: 320px)" );
  mq.addListener(function(){
    if (mq.matches) {
      ...
    }
  });

All wrapped in $(function(){...}); because I used jQuery animations when matched.




回答3:


this one will work.

  $(function () {

//1) create a function 
        var handleMatchMedia = function(md) {
            if (md.matches) {
               // your code
            } else {
               // your code
            }
        }
        var mq = window.matchMedia("(max-width: 768px)");

 // 2) call the function
        handleMatchMedia(mq);


//3) call the addListener function  
        mq.addListener(handleMatchMedia);
      });

P.S. the addListener function can be found in Typescript, so make sure you downloaded Typescript .

also read this article:

http://blog.astaz3l.com/2013/11/27/matchmedia/



来源:https://stackoverflow.com/questions/11364986/jquery-media-queries-with-match-media

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