简体   繁体   English

如何动态更改字体大小并添加最小字体大小?

[英]How can i dynamicly change the font size and add a minimal font-size?

I want to change the font-size depending of the width of my browser window. 我想根据浏览器窗口的宽度更改font-size

The font is resizing while i resize the browser window, but it doesn't prevent the font-size going under 18px. 当我调整浏览器窗口的大小时,字体正在调整大小,但这并不能防止font-size小于18px。

  font_size();
  function font_size(ww,wh) {
    var title = document.getElementById("title").style.fontSize;
    if (title < 18) {
      $("#title").css("font-size", 18);
    }else{
      $("#title").css("font-size", ww*0.0315);
    }
  };

What's the issue with my code? 我的代码有什么问题?

Can we see your HTML? 我们可以看到您的HTML吗?

The .style method on DOM elements would most likely give you the styles that has been added to that element using the style attribute and not any other internal or external CSS. DOM元素上的.style方法很可能会为您提供使用style属性(而不是任何其他内部或外部CSS)添加到该元素的style

To fix that either use jQuery's .css() method or browser's inbuilt getComputerStyle() function. 要解决此问题,请使用jQuery的.css()方法或浏览器的内置getComputerStyle()函数。

Another point is that .style() , .css() and getComputedStyle() all returns strings and not numbers, so it is wise to parse the strings to numbers before using any comparison operators. 另一点是, .style() .css()getComputedStyle()的所有返回的字符串,而不是数字,那么明智的做法是使用任何比较操作之前,解析字符串的数字。

if ( parseInt(title) < 18) {

These two problems can be the cause. 这两个问题可能是原因。 Sort it out and see if it works. 整理一下,看看是否可行。

You don't need Javascript for this. 您不需要使用Javascript。 CSS is up to the challenge. CSS迎接了挑战。

#title {
  font-size: 18px;
}

@media (min-width: 572px) {
  #title {
    font-size: 3.15vw;
  }
}

This sets #title 's font-size to 18px, unless the viewport is at least 572 pixels wide. 除非视口的宽度至少为572像素,否则这#titlefont-size为18px。 At that size and wider, #title 's font-size is 3.15% of the viewport's width. 在该尺寸和更大的尺寸下, #titlefont-size视口宽度的3.15%。 (My console tells me 3.15% of 572px is 18.018px, and it increases from there.) (我的控制台告诉我572px的3.15%是18.018px,并且从那里开始增加。)

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

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