javascript - 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>
解决方案
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?
推荐阅读
- android - 使用哪种架构来检索数据库更新
- sql - 当合并空列不合并时,刚刚插入
- c - 返回 int 数组的 Printf 函数
- java - RequestParam = false 不返回所有内容
- spring - 为什么 Spring boot AspectJ 有时只错过触发
- flutter - 即使在颤振中重新启动应用程序后如何保持相同状态
- c# - 为什么功能区项目没有显示在窗口上?
- sql - SQL 连接日期和日期 - 如果未找到匹配项,则返回最新的
- selenium-webdriver - 如何阻止弹出窗口出现在 Jmeter WebDriver Sampler 上
- java - 需要对人们在测试中使用的不同用例进行一些解释