简体   繁体   English

根据屏幕宽度调整字体大小

[英]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 如果屏幕宽度小于1100像素,有人可以通过JavaScript代码帮助我调整div中字体的大小吗?

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. 您的代码在JS Fiddle中对我有用。 Perhaps you are not specifying the correct id for your div or something like that. 也许您没有为您的div或类似名称指定正确的ID。

http://jsfiddle.net/trott/GqFPY/ 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: 您将需要将动作绑定到window.onresize事件:

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. 我在一个博客中发布了有关更改字体大小的信息,但这是为了说明如何使用jQueryUI滑块。 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 http://weblogs.asp.net/thiagosantos/archive/2009/03/21/my-first-time-with-jquery-ui.aspx

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

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