jQuery - 根据屏幕大小执行脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17237935/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery - Execute scripts based on screen size
提问by Dean Elliott
Is it possible to only run certain jQuery scripts if the screen/device size is above xxx pixels wide?
如果屏幕/设备尺寸大于 xxx 像素宽,是否可以只运行某些 jQuery 脚本?
So, for example, I only want to run a slideshow when people are viewing the site on devices bigger than 1024px. If someone visits on a mobile I just want all the images to display stacked on top of each other...
因此,例如,当人们在大于 1024 像素的设备上查看网站时,我只想运行幻灯片。如果有人在手机上访问,我只希望所有图像堆叠显示...
回答by Mohammad Adil
You can use $(window).width()
您可以使用 $(window).width()
if($(window).width() >= 1024){
// do your stuff
}
Demo --->
http://jsfiddle.net/fh2eC/1/
回答by Shaddow
If you want to check width size after windows is resized then:
如果要在调整窗口大小后检查宽度大小,则:
$(window).resize(function() {
if( $(this).width() > width ) {
// code
}
});
回答by jcreamer898
You might also consider a library like https://github.com/paulirish/matchMedia.js/
您也可以考虑使用像https://github.com/paulirish/matchMedia.js/这样的库
if (matchMedia('only screen and (max-width: 480px)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
}
回答by Werner ZeBeard Bessinger
Just use the following:
只需使用以下内容:
if($(window).width() >= 1024){
//your code here
}
This works, but remember to put the script at the end of your page rather than at the beginning, otherwise you'll end up having mixed results. I'd also avoid using it inside a document.ready() event if you're planning to use it to apply styles of any sort as there might be a slight but noticeable delay in applying said styles.
这是有效的,但请记住将脚本放在页面的末尾而不是开头,否则最终会出现混合结果。如果您打算使用它来应用任何类型的样式,我也会避免在 document.ready() 事件中使用它,因为在应用所述样式时可能会有轻微但明显的延迟。