简体   繁体   中英

Changing font size of a JavaScript number variable

I want to change the font size of a number that is assigned to a variable and then printed out.

var secondsPerMinute = 60;
var minsPerHour = 60;

var hoursPerDay = 24;
var daysPerWeek = 7;
var weeksPerYear = 52;
var secondsPerDay =  secondsPerMinute*minsPerHour*hoursPerDay;
document.write(secondsPerDay);
var alpha = "blah";
document.write(alpha.fontsize(10));

Here I want to change the font size of the output secondsPerDay .. for some reason .fontsize() does not work on it. I am new to javascript so apologies if this seems like a foolish question.

According to the MDN page on String#fontsize :

Deprecated
This feature has been removed from the Web standards. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

Nor should you use document.write , for many reasons .

Write output into HTML elements defined on your page, styled using CSS. For example:

<span id="secondsPerDay" style="font-size: 10px; "></span>
document.getElementById('secondsPerDay').textContent = secondsPerDay;

change the last line to

document.write("<span style='font-size:10px;'>"+secondsPerDay+"</span>");
document.write("<span style='font-size:10px;'>"+alpha+"</span>");

use font-size property of the css

after checking @torazaburo's answer, try to use innerHTML rather than document.write

document.body.innerHTML += "<span style='font-size:10px;'>"+secondsPerDay+"</span>";
document.body.innerHTML += "<span style='font-size:10px;'>"+alpha+"</span>";

EDIT:

The fontsize function is a deprecated method from the String object and you should avoid using it. See some of the other solutions people have posted as a safer alternative.

I recommend outputting HTML and setting the font-size using inline CSS:

document.write('<span style="font-size: 10px">' + secondsPerDay + '</span>');
                             ^^^^^^^^^^^^^^^

Updated fiddle


You have to also apply fontsize() to the secondsPerDay :

 
 
 
 
  
  
  document.write(secondsPerDay.toString().fontsize(10));
 
 
  

See your working code here .

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