简体   繁体   中英

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.

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.

You can try this Pure CSS Solution in which your HTML stays the same and this will be performant also. No Javascript is needed then.

PURE CSS SOLUTION:

 #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:

You don't require these many checks to show two text messages. Below code sums it up with just two if-else conditions. Try to resize your 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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