【问题标题】:How to Detect Window Width w/ Javascript如何使用 Javascript 检测窗口宽度
【发布时间】:2015-02-07 20:12:19
【问题描述】:

这就是我目前所得到的:

<!DOCTYPE html>
<html>
<head>
    <title>Fonts!</title>
    <link rel="stylesheet" href="fonts.css">
</head>
<body>
    <h1 id="Hagin">Hello.</h1>
    <h2 id="Hagin2">Goodbye.</h2>

    <p class="Glober">Hello. This is a paragraph. It is meant to test this font. What do you think? Do you like this font? I think I do, although I'm not sure. That's why I'm writing this paragraph. Eh? Bigger you say? I agree. Let's make it bigger. Yeah, you know what, I'm using this. Allong with that Hagin thing. Some sexy shit.</p>

    <div></div>

    <script type="text/javascript">
    var width = window.innerWidth;

    if (width < (300 + "px")) {
        window.alert("It works!");
    }
    </script>
</body>
</html>

当窗口降到 300 像素以下时,什么也没有发生。我正在使用谷歌浏览器。我也试过了

if (width < 300) {

但这也没有用。想法?

【问题讨论】:

  • 您的代码仅在页面加载时执行ONCE,然后再也不会执行。您需要将该代码附加到事件处理程序,以便响应事件按需执行 - 例如调整窗口大小。
  • 怎么样?我会使用什么事件处理程序?也许整个文档的onmouseover?看起来很烦人...

标签: javascript html window width


【解决方案1】:

试试...

window.onresize = function(event) {
    var width = window.innerWidth;

    if (width < 300) {
        alert("It works!");
    }
};

这将在每次调整窗口大小时触发事件。

【讨论】:

    【解决方案2】:

    我认为这里的问题在于条件语句。我不相信 javascript 了解如何将窗口宽度(基本整数)与字符串(“300px”)进行比较。尝试删除条件的 (+ "px") 位,使其看起来像这样:

    var width = window.innerWidth;
    
    if (width < (300)) {
        window.alert("It works!");
    }
    

    这应该可以解决问题。

    【讨论】:

      【解决方案3】:
      var resized;
      $(window).on('resize orientationChanged', function(){
        clearTimeout(resized);
        resized = setTimeout(function () {
          var width = window.innerWidth;
      
          if (width < 300) {
            window.alert("It works!");
          }
        }, 200);
      });
      

      这可能会奏效。

      【讨论】:

        猜你喜欢
        • 2012-03-31
        • 2010-10-10
        • 1970-01-01
        • 2012-05-31
        • 1970-01-01
        • 2017-01-16
        • 2017-07-26
        • 2019-10-03
        • 2014-05-20
        相关资源
        最近更新 更多