按钮宽度和高度固定,字体大小根据字数自适应用的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>
其中按钮的高度固定为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>
相关文章推荐
- JSP简单介绍
- JavaScript弹出新窗口的方法
- 翻译:谷歌HTML、CSS和JavaScript风格规范
- JSP基础整理
- 修改jsp页面标题左边的图标
- 使用Jackson的@JsonFormat注解时出现少八个小时
- javaScript 正则表达式匹配日期
- 移动web滑动效果Swipe JS插件
- JS设置弹出小窗口。
- 基于 phantomjs 的自动化测试---(1)
- 报表软件JS开发引用HTML DOM的location和document对象
- JavaScript中发布/订阅模式的简单实例
- JavaScript基础
- JavaScript 获取鼠标点击位置坐标
- js的一个有意思的小题,闭包解决getElementByTagName的for循环绑定事件错误问题
- WEB页面JS实现一键拨号的电话拨打功能
- doT.js初学代码
- day13 JS Dom
- JS开发引用HTML DOM的location和document对象
- JS开发引用HTML DOM的location和document对象