【问题标题】:javascript change text when change width devicejavascript在更改宽度设备时更改文本
【发布时间】: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


【解决方案1】:

更新:我提供了一个 Javascript 解决方案,但对于这个小任务,我认为使用 javascript 是一种矫枉过正。

您可以尝试这个纯 CSS 解决方案,在该解决方案中,您的 HTML 保持不变,而且性能也很好。那时不需要 Javascript。

纯 CSS 解决方案:

#TextStartUp{
  position:relative;
}
#TextStartUp::after{
  position:absolute;
  left:0;
  top:0;
  content:"touch the screen to continue"
}

@media(min-width:1024px){
  #TextStartUp::after{
     content:"Press any key to continue."
  }
&lt;div id="TextStartUp"&gt;&lt;/div&gt;

JAVASCRIPT 解决方案:

您不需要进行这么多检查即可显示两条短信。下面的代码仅用两个 if-else 条件对其进行了总结。尝试调整窗口大小:)

if(window.innerWidth<=1024){
  document.getElementById('TextStartUp').innerHTML = 'touch the screen to continue.';
}

if(window.innerWidth >1024){
     document.getElementById('TextStartUp').innerHTML = 'Press any key to continue.';
}
 
// To see changes try to resize developer console

window.addEventListener("resize",()=>{
    if (window.innerWidth <= 1024) { //tablet landscape and below screens
    document.getElementById('TextStartUp').innerHTML = 'touch the screen to continue.';
}
else if (window.innerWidth > 1024) { //laptop and above screens
    document.getElementById('TextStartUp').innerHTML = 'Press any key to continue.';
}
})
&lt;div id="TextStartUp"&gt;&lt;/div&gt;

【讨论】:

  • 是的。但我想补充一下,在任意屏幕尺寸(每个设备)上“触摸屏幕”或“按任意键”的整个概念在 UI/UX 级别上有点疯狂。考虑到键盘可以连接到较小的设备。消息应该简单地提及两者。
  • 还有屏幕触摸和按键事件 :) 但浏览器支持可能会有所不同。但是是可以实现的:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
  • 2011-09-30
  • 2023-04-03
相关资源
最近更新 更多