更改宽度设备时javascript更改文本

时间:2021-01-10 11:27:52

标签: javascript html responsive

大家好,当设备宽度发生变化时,我想更改屏幕上显示的文字,我用 javascript 编写了这段代码,但它不会改变文字,只给我最后一个正确的选项。< /p>

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.';
}

1 个答案:

答案 0 :(得分:0)

更新:我已经提供了一个 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."
  }
<div id="TextStartUp"></div>

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.';
}
})
<div id="TextStartUp"></div>