JS控制网页字体大小(原生js和JQuery两种写法)
方法一:
原生js
window.onload= function(){
var oPtxt=document.getElementById("article");
var oPtable=$("#article table")[0];
var oBtn1=document.getElementById("enlarge");
var oBtn2=document.getElementById("narrow");
var num = 14; /*定义一个初始变量*/
oBtn1.onclick = function(){
num++;
oPtxt.style.fontSize=num+'px';
oPtable.style.fontSize=num+'px';
};
oBtn2.onclick = function(){
num--;
oPtxt.style.fontSize=num+'px';
oPtable.style.fontSize=num+'px';
}
}方法二:
JQuery
$(function(){
$("span").click(function(){
var thisEle = $("#article").css("font-size");
var textFontSize = parseInt(thisEle , 10);
var unit = thisEle.slice(-2); //获取单位
var cName = $(this).attr("id");
if(cName == "enlarge"){
if( textFontSize <= 22 ){
textFontSize += 2;
}
}else if(cName == "narrow"){
if( textFontSize >= 12 ){
textFontSize -= 2;
}
}
$("#article").css("font-size", textFontSize + unit);
});
});html代码:
<!--按钮--> <span id="enlarge" title="字体放大">放大</span><span id="narrow" title="字体缩小">缩小</span> <!--控制文本--> <div id="article">控制这里的文字</div>
本文链接:https://h.finchui.com/wangzhan/4657.html 转载需授权!











在线咨询