简体   繁体   English

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

[英]javascript change text when change width device

Hi everyone I would like to change the writing that comes on the screen when the width of the device changes, I made this code in javascript, but it doesn't change the writing and gives me only the last option correct.大家好,我想在设备宽度发生变化时更改屏幕上出现的文字,我在 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.';
}

UPDATE: I have provided a Javascript solution but for this small task, I believe going with javascript is an overkill.更新:我提供了一个 Javascript 解决方案,但对于这个小任务,我相信使用 javascript 是一种矫枉过正。

You can try this Pure CSS Solution in which your HTML stays the same and this will be performant also.您可以尝试这个纯 CSS 解决方案,其中您的 HTML 保持不变,这也将是高性能的。 No Javascript is needed then.然后不需要 Javascript。

PURE CSS SOLUTION:纯 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 SOLUTION: JAVASCRIPT 解决方案:

You don't require these many checks to show two text messages.您不需要进行这么多检查即可显示两条短信。 Below code sums it up with just two if-else conditions.下面的代码仅用两个 if-else 条件对其进行了总结。 Try to resize your window:)尝试调整您的 window 的大小:)

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM