首页 > 解决方案 > Javascript:innerWidth 的条件不起作用

问题描述

我正在尝试在不同的屏幕分辨率上实现不同的样式。

我试过if(window.innerWidth >= ) {}了,但它不起作用。假设我希望当屏幕分辨率小于 768px 时 h1 的颜色为蓝色,即使屏幕宽度大于定义的宽度,样式也会立即改变。

请看下面的代码:

<h1 id="change" style="color: red;";>Hello</h1>

<script>

  if(window.innerWidth <= 768){
    document.getElementById("change").style.color = "blue";
  }

</script>

标签: javascriptcss

解决方案


Your snippet only gets run once on load. You´d have to set this snippet in a loop so it gets tested again and again. There is a EventListener called "resize" which you could use.

window.addEventListener("resize", () => {
        if (window.innerWidth <= 768) {
            document.getElementById("change").style.color = "blue";
        }
});

Why dont you use css media queries?


推荐阅读