如何使用/ Javascript检测窗口宽度

时间:2014-12-09 19:37:58

标签: javascript html window width

所以这就是我到目前为止所做的:

<!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像素时,没有任何反应。我正在使用Google Chrome。我也试过了

if (width < 300) {

但这也不起作用。想法?

3 个答案:

答案 0 :(得分:0)

尝试......

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

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

每次窗口调整大小时都会触发事件。

答案 1 :(得分:0)

我认为这里的问题是条件陈述。我不相信javascript了解如何比较窗口宽度(基本整数)和字符串(&#34; 300px&#34;)。尝试删除条件的(+&#34; px&#34;)位,使其看起来像这样:

var width = window.innerWidth;

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

这应该可以解决问题。

答案 2 :(得分:0)

var resized;
$(window).on('resize orientationChanged', function(){
  clearTimeout(resized);
  resized = setTimeout(function () {
    var width = window.innerWidth;

    if (width < 300) {
      window.alert("It works!");
    }
  }, 200);
});

这可能会奏效。