仅当窗口大于X

时间:2016-01-24 02:06:04

标签: javascript responsive-design

我目前正在使用下面的脚本,但发现它只适用于屏幕大小,而不适用于窗口大小,因此调整浏览器大小不会触发它。如何在屏幕尺寸大于X时才能运行?是否有任何考虑我应该考虑视网膜显示?

<script>
if (screen && screen.width > 899) {
document.write('<script async type="text/javascript" src="http://example.com/myscript.js"><\/script>');
}
</script>

2 个答案:

答案 0 :(得分:3)

这可以通过window.matchMediadocs

来完成
<script>
  var mediaQuery = window.matchMedia('(min-width: 400px)');

  mediaQuery.addListener(loadScripts);

  function loadScripts() {
    document.write('\x3Cscript src="myScript.js">\x3C/script>');
  }    
</script>

<script src="mySecondScript.js"></script>
<script src="myThirdScript.js"></script>

这是JSFiddle

答案 1 :(得分:0)

而不是screen使用window

&#13;
&#13;
var out = document.getElementById('out');
var foo = function() {
  console.log('resized ...');
  if (window.innerWidth > 899) {
    alert('load script');
  }
  out.innerHTML = window.innerWidth;
};

window.onresize = foo; // run code on window resize

foo(); //run code on page load
&#13;
Resize window, width: <span id="out"></span>px
&#13;
&#13;
&#13;