问题
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