Dou*_*Fir 12 javascript media-queries
我在这里匆匆忙忙地寻找一两行代码:
有人可以善待提供代码放在html doc的head部分,说如果移动然后不加载JS?
这与以下CSS媒体查询一起使用:
<link rel="stylesheet" type="text/css" media="only screen and (max-device-width: 480px)" href="m/styles_mobile.css" />
Run Code Online (Sandbox Code Playgroud)
所以我正在寻找一条基于相同规则的代码:media ="only screen and(max-device-width:480px)"
会非常感激的
Rob*_*obG 24
鉴于:"如果移动然后不加载JS ",并假设"移动"由宽度为480像素或更小的屏幕定义,那么类似下面的内容应该工作:
<script>
if (screen && screen.width > 480) {
document.write('<script type="text/javascript" src="foo.js"><\/script>');
}
</script>
Run Code Online (Sandbox Code Playgroud)
仅当屏幕宽度超过480像素时才会添加脚本元素.
OP中的CSS规则是:
<... media="only screen and (max-device-width: 480px)" ...>
Run Code Online (Sandbox Code Playgroud)
这将针对480像素或更少的屏幕,这与第一个声明相反.因此>,<=如果脚本应该在小屏幕上运行而不在较大的屏幕上运行,则更改为.
Dav*_*ave 12
我不确定以前的答案如何与视网膜显示器一起使用.我会做的事情如下:
if( /Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent))
document.write('<script type="text/javascript" src="foo.js"><\/script>');
Run Code Online (Sandbox Code Playgroud)
来自这里的片段
现在可以使用 window.matchMedia
if (window.matchMedia("(min-width: 480px)").matches) {
document.write('<script type="text/javascript" src="foo.js"><\/script>');
}
Run Code Online (Sandbox Code Playgroud)
https://developer.mozilla.org/docs/Web/API/Window/matchMedia http://caniuse.com/#feat=matchmedia
你可以这样做.
你能做的是:
var scripts = ["foo.js", //Put all your scripts here.
"bar.js"];
if(screen.width <= 480){
for(var i=0;i<scripts.length;i++){
//-with jQuery (one line!)-
$("head").append('<script type="text/javascript" src="'+scripts[i]+'"><\/script>');
//-or jQuery free-
var scriptEle = document.createElement("script");
scriptEle.setAttribute("type","text/javascript");
scriptEle.setAttribute("src",scripts[i]);
document.getElementsByTagName("head")[0].appendElement(scriptEle);
}
}
Run Code Online (Sandbox Code Playgroud)
注意它是screen.width <= 480.