简体   繁体   中英

Resizing font based on screen width

Can someone help me with JavaScript code that resizes a font in a div if the screen width is lower than 1100px

if (window.screen.width <= 1100) {
  var item = document.getElementById("div1");
  item.style.fontSize = "25px";
  item.innerHTML = "String";
}

This is what I have so far. Can someone help me with what to do next?

Your code works for me in JS Fiddle. Perhaps you are not specifying the correct id for your div or something like that.

http://jsfiddle.net/trott/GqFPY/

If you are hoping the code will be triggered on a browser resize, you will need to bind it to an event. (See Michael's answer.)

You will need to bind the action to the window.onresize event:

var resizeFonts = function() {
  var item = document.getElementById("div1");
  if (window.screen.width <= 1100) {
      item.style.fontSize = "25px";
      item.innerHTML = "String";
  }
  // Otherwise set a larger font
  else item.style.fontSize = "30px";
};

window.onload = resizeFonts;
window.onresize = resizeFonts;

I have an OLD blog in which I posted about changing the font size, but it was made to show how to use jQueryUI slider. Maybe you can use some of the logic there to create your own solution:

http://weblogs.asp.net/thiagosantos/archive/2009/03/21/my-first-time-with-jquery-ui.aspx

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