您的位置:首页 > Web前端 > JavaScript

按钮宽度和高度固定,字体大小根据字数自适应用的javascript实现

2016-04-25 15:10 891 查看
演示效果如下:



其中按钮的高度固定为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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: