基于媒体查询的可选Javascript执行 [英] Optional Javascript Execution based on Media Queries
问题描述
我想知道如何根据当前的设备/媒体查询可以选择运行一个javascript块。我使用Twitter Bootstrap并且基本上有两个版本的媒体查询:
I'm trying to figure out how I can optionally run a block of javascript based on the current device/media query. I'm using Twitter Bootstrap and have essentially two versions of media queries:
@media (min-width: 980px) { ... } <!-- Desktops -->
@media (max-width: 979px) { ... } <!-- Smaller screens/tablets/phones -->
我有一个我生成的地图,但没有显示在手机/小屏幕版本中forb带宽原因。然而,JavaScript仍然在后台执行,即使你不能在移动屏幕上看到它。所以,我想在javascript中找到一种方法,我可以做类似的:
I have a map that I generate, but am not showing it in the mobile/small screen version forb andwidth reasons. Yet, the javascript still executes in the background even though you can't see it on the mobile screen. So, I'm trying to find a way in javascript where I can do something like:
// Imaginary function
var screenType = getScreenType();
if(screenType == 1) {
// Load map
}
我已阅读人们将CSS属性设置为特定值在他们的媒体查询,然后试图找到基于CSS属性的DOM中的元素,但必须有一个更好的方法。任何想法?
I've read about people setting CSS properties to specific values in their media queries and then trying to find that element in the DOM based on the CSS property, but there has got to be a better way. Any ideas?
推荐答案
如何使用javascript?
How about using javascript for that?
<script type="text/javascript">
if (screen.width < 980) {
document.write('<link href="UrLowRes.css" type="text/css" rel="stylesheet"/>');
} else {
document.write('<link href="UrlHighRes.css" type="text/css" rel="stylesheet"/>');
}
</script>
这篇关于基于媒体查询的可选Javascript执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!