【问题标题】:Run code if screen has certain width如果屏幕有一定宽度则运行代码
【发布时间】:2017-01-26 04:52:32
【问题描述】:

我只是想在窗口大小小于 700 像素时在控制台中写一条消息。

我尝试过的事情是:

if(window.innerWidth < 700){
console.log("hello");
}

if(screen.width < 700){
console.log("hello");
}

我没有收到任何错误消息,但代码没有运行。如果我在 700 之后添加“px”,则会收到错误消息“Uncaught SyntaxError: Unexpected identifier”。

【问题讨论】:

    标签: javascript if-statement width screen


    【解决方案1】:

    您需要将它放在windowresize 事件侦听器中。而且你还需要使用window.innerWidth,它总是返回一个整数值。

    if (window.attachEvent) {
      window.attachEvent('onresize', function() {
        if (window.innerWidth < 760)
          console.log("Less than 760");
        else
          console.log("More than 760");
      });
    } else if (window.addEventListener) {
      window.addEventListener('resize', function() {
        if (window.innerWidth < 760)
          console.log("Less than 760");
        else
          console.log("More than 760");
      }, true);
    } else {
      //The browser does not support Javascript event binding
    }

    【讨论】:

    • 附带说明,根据需要的浏览器支持,最好的方法是使用window.matchMedia(mediaQueryString)
    • @A.Wolff 感谢您的想法...我不知道。 :)我会看看它并相应地更新我的答案......
    • 我对 javascript 很陌生,还没有使用过 .attachEvemt 和 .添加事件监听器。我让我的代码可以工作,但我必须阅读一下代码的实际作用以及它为什么工作。无论如何,谢谢!很好的答案!
    【解决方案2】:

    您需要在 'window' 上监听 'resize' 事件:

    window.addEventListener('resize', resize);
    
    function resize() {
    
        if (window.innerWidth < 700) {
    
            console.log('window.innerWidth < 700');
            // window.removeEventListener('resize', resize); // once
        }
    }
    

    关于 .addEventListener 的更多信息:https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

    【讨论】:

    • 您应该提供更多信息......这个答案比我的更好吗?只是好奇,不是责备...:)
    • 谢谢你让代码工作,但我必须阅读第一行,我之前没有使用过 .addEventListener。
    • @PraveenKumar 当我写这个答案时没有答案。
    • @williamganrot 你是对的,对此感到抱歉。我认为您可以在任何地方阅读有关“addEventListener”的信息。如果您仍想了解更多信息,这是正确的地方:developer.mozilla.org/en-US/docs/Web/API/EventTarget/…
    • @AbdullahAydın 当然... :)
    【解决方案3】:
    onResize();
    window.addEventListener('resize', onResize);
    
    function onResize(){
        var width = document.documentElement.clientWidth;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-03
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 1970-01-01
      相关资源
      最近更新 更多