如何有条件地使用 javascript,如 CSS3 媒体查询、方向?
例如我可以为特定的东西写css
@media only screen and (width : 1024px) and (orientation : landscape) {
.selector1 { width:960px}
}
现在我只想运行一些符合相同条件的 javascript
喜欢
@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
它应该只运行在特定的屏幕尺寸和方向
最佳答案
您可以使用 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
}
目前所有现代浏览器都支持 ( more details )
旧浏览器的 Polyfill: https://github.com/paulirish/matchMedia.js/
关于javascript - 如何有条件地使用 javascript,如 CSS3 媒体查询、方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7625718/