【发布时间】:2021-01-10 20:12:39
【问题描述】:
大家好,我想在设备宽度发生变化时更改屏幕上出现的文字,我用 javascript 编写了这段代码,但它并没有改变文字,只给了我最后一个正确的选项。
var heightDevice = document.getElementById('startup-animation').offsetHeight;
var widthDevice = document.getElementById('startup-animation').offsetWidth;
console.log(widthDevice);
if (widthDevice <= 480) { //smartphone
document.getElementById('TextStartUp').innerHTML = 'touch the screen to continue.';
}
else if (widthDevice <= 768) { //tablet
document.getElementById('TextStartUp').innerHTML = 'touch the screen to continue.';
}
else if (widthDevice <= 1024) { //tablet landscape
document.getElementById('TextStartUp').innerHTML = 'touch the screen to continue.';
}
else if (widthDevice <= 1680) { //laptop
document.getElementById('TextStartUp').innerHTML = 'Press any key to continue.';
}
else if (widthDevice > 1680) { //desktop
document.getElementById('TextStartUp').innerHTML = 'Press any key to continue.';
}
【问题讨论】:
-
它是一种古老的技术(你正在使用的方式)并且可以工作。但是您是否研究过响应式设计和媒体查询?两者都可以根据需要在某些场景中组合使用,快速修复的 javascript 方式。
-
是否只是改变文本而不是页面的样式,通过媒体查询我可以改变文本,还是您建议制作几个段落并在屏幕上只显示相关的一个媒体查询?
-
改用 window.innerWidth 试试看结果如何 :)
-
实际上只有 CSS 解决方案:stackoverflow.com/questions/39894291/…
-
确实是@ImranRafiqRather
标签: javascript html responsive