简体   繁体   中英

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.

The font is resizing while i resize the browser window, but it doesn't prevent the font-size going under 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?

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.

To fix that either use jQuery's .css() method or browser's inbuilt getComputerStyle() function.

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.

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. CSS is up to the challenge.

#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. At that size and wider, #title 's font-size is 3.15% of the viewport's width. (My console tells me 3.15% of 572px is 18.018px, and it increases from there.)

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