Controlling Font Size With Javascript

The following script can be used to allow visitors to increase or decrease the size of text on your page. This can be useful for visitors who have trouble reading smaller text and allows them to increase it to something they can view more easily.

Decrease Font Size Increase Font Size

This script will change the font size of any text within a paragraph (<p> tag). If you wish to change text within other tags edit the getElementsByTagName('p'); part.

In order for this code to work your page must be using pixel sized fonts (px) rather than relative sized fonts using 'em' or '%'. Of course if you do use other font units the code can be easily adapted for these. If the script cannot find the font size of a paragraph it will default it to 12px.

If you find this script useful then please consider making a donation to the developer

<script type="text/javascript"> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script> width="468" scrolling="no" height="60" frameborder="0" allowtransparency="" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-7790596295547222&dt=1207856772203&lmt=1207856772&output=html&slotname=0781836016&correlator=1207856772203&url=http%3A%2F%2Fwww.white-hat-web-design.co.uk%2Farticles%2Fjs-fontsize.php&frm=0&cc=100&ga_vid=600689931.1207856772&ga_sid=1207856772&ga_hid=1991655679&flash=9.0.115.0&u_h=1024&u_w=1280&u_ah=964&u_aw=1280&u_cd=32&u_tz=480&u_his=2&u_java=true" marginheight="0" marginwidth="0" name="google_ads_frame">

The code

var min=8;
var max=18;
function increaseFontSize() {
var p = document.getElementsByTagName('p');
for(i=0;i<p.length;i++) {
if(p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px",""));
} else {
var s = 12;
}
if(s!=max) {
s += 1;
}
p[i].style.fontSize = s+"px"
}
}
function decreaseFontSize() {
var p = document.getElementsByTagName('p');
for(i=0;i<p.length;i++) {
if(p[i].style.fontSize) {
var s = parseInt(p[i].style.fontSize.replace("px",""));
} else {
var s = 12;
}
if(s!=min) {
s -= 1;
}
p[i].style.fontSize = s+"px"
}
}

Usage

Include the above code in your page (either by placing it within the head section or placing it in an external js file and importing it). You can then call the increase and decrease font size functions like below.

<a href="javascript:decreaseFontSize();">-</a> 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值