演示效果如下:
其中按钮的高度固定为40px,按钮的宽度固定为60px,字体大小根据宽度自适应。
具体代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<div>
<br><br>
<input type="button" value="A"/>
<input type="button" value="AB"/>
<input type="button" value="ABC"/>
<br><br>
<input type="button" value="ABCD"/>
<input type="button" value="ABCDE"/>
<input type="button" value="ABCDEF"/>
</div>
</body>
<script type="text/javascript">
var maxHeight=40; //固定高度
var maxWidth=60; //固定宽度
var height=[];
var width=[];
var button=document.getElementsByTagName("input");
for(var i=0;i<button.length;i++){
button[i].style.fontSize="8px";
height[i]=button[i].offsetHeight;
width[i]=button[i].offsetWidth;
while(parseInt(height[i])<maxHeight&&parseInt(width[i])<maxWidth){ //逐次递增字体大小,使字体达到最大的字号
button[i].style.fontSize=parseInt(button[i].style.fontSize)+1+"px";
height[i]=button[i].offsetHeight;
width[i]=button[i].offsetWidth;
}
button[i].style.width="60px";
button[i].style.height="40px";
}
</script>
</html>