如何像 CSS3 媒体查询、方向一样有条件地使用 javascript? [英] How to use javascript conditionally like CSS3 media queries, orientation?
问题描述
如何像 CSS3 媒体查询、方向一样有条件地使用 javascript?
How to use javascript conditionally like CSS3 media queries, orientation?
例如我可以为特定编写css
For Example I can write css for specific
@media only screen and (width : 1024px) and (orientation : landscape) {
.selector1 { width:960px}
}
现在我只想运行一些符合相同条件的javascript
Now I want to only run some javascript if it match the same conditions
喜欢
@media only screen and (width : 1024px) and (orientation : landscape) {
A javascript code here
}
我有一个外部 javascript,例如 http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js
它应该只在特定的屏幕尺寸和方向
I have a external javascript for example http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js
and it should be only run on specific screen size and orientation
推荐答案
您可以使用 window.matchMedia():
测试移动设备媒体查询
if (matchMedia('only screen and (max-width: 480px)').matches) {
// smartphone/iphone... maybe run some small-screen related dom scripting?
}
测试横向
if (matchMedia('all and (orientation:landscape)').matches) {
// probably tablet in widescreen view
}
目前在所有现代浏览器中均受支持(更多详情)
Currently supported in all modern browsers (more details)
旧浏览器的 Polyfill:https://github.com/paulirish/matchMedia.js/
Polyfill for old browsers: https://github.com/paulirish/matchMedia.js/
这篇关于如何像 CSS3 媒体查询、方向一样有条件地使用 javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!