简体   繁体   English

如何使用Javascript检测窗口宽度

[英]How to Detect Window Width w/ Javascript

So this is what I've got so far: 所以这就是我到目前为止所得到的:

<!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>

And when the window drops below 300 px, nothing happens. 当窗口降到300 px以下时,什么也没有发生。 I'm using Google Chrome. 我正在使用Google Chrome。 I also tried just 我也尝试过

if (width < 300) {

but that didn't work either. 但这也不起作用。 Ideas? 有想法吗?

Try ... 尝试...

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

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

This will fire the event each time the window resizes. 每次调整窗口大小时都会触发该事件。

I think the issue here is with the conditional statement. 我认为这里的问题在于条件声明。 I don't believe javascript understands how to compare the window width (a basic integer) with a string ("300px"). 我不相信javascript了解如何将窗口宽度(基本整数)与字符串(“ 300px”)进行比较。 Try removing the (+ "px") bit of your conditional so it looks like this: 尝试删除条件中的(+“ px”)位,使其看起来像这样:

var width = window.innerWidth;

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

That should do the trick. 这应该够了吧。

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

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

This would probably work. 这可能会起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM