1. 字符串大小写转换
- - 编写HTML表单,设置两个文本框和两个按钮,文本框显示转换前后数据,按钮用于转 换。
-- 为按钮添加点击事件,并利用函数处理。
-- 编写函数,根据传递的不同参数执行不同的转换操作。
-- 将转换后的数据显示到对应位置。
css样式:好久没写,不太熟练了,不写也行问题不大。
<style>
.text{
margin:200px auto;
margin-left: 200px;
}
.form{
width:420px;
margin:100px auto;
height:600px;
}
.item{
width:420px;
height:60px;
font-size: 18px;
}
input{
width:240px;
padding:5px 5px;
height:28px;
font-size: 18px;
margin-left: 20px;
text-decoration: none;
border-radius: 6px;
border:1px solid #ccc;
outline: none;
}
.btn{
width:420px;
height:60px;
}
button{
width:120px;
padding:5px 5px;
height:40px;
border-radius: 6px;
border:1px solid #ccc;
outline: none;
box-sizing: border-box;
}
.Capitalize-btn{
margin-right: 158px;
}
</style>
html代码:
<div class="text">
<form action="transform">
<div class="item item01">
字符转换前: <input id="old" type="text" placeholder="请输入转换前的字符">
</div>
<div class="item item02">
字符转换后: <input id="new" type="text" placeholder="请输入转换后的字符">
</div>
<div class="btn">
<button class="Capitalize-btn" value="转换为大写" onclick="transform('upper')">转换为大写</button>
<button class="lowercase-btn" value="转换为小写" onclick="transform('lower')">转换为小写</button>
</div>
</form>
</div>
JavaScript代码:
<script>
function transform(i){
var str_old=document.getElementById('old').value;
switch(i){
case 'upper':
str=str_old.toUpperCase();
break;
case 'lower':
str = str_old.toLowerCase();
break;
}
document.getElementById('new').value= str;
}
</script>
2 .封装函数,求2个数中的最大值 求出求两个数中的最大值;求出三个数中的最大值。
代码:
<script>
function getMaxNum(a, b,c=-999) {
if(a>=b && a>=c){
return a;
}else if(b>=a && b>=c) {
return b;
}else{
return c;
}
}
var max_num= getMaxNum(Number(prompt('请输入要比较的第一个数')), Number(prompt('请输入要比较的第二个数')), Number(prompt('请输入要比较的第三个数,可不填')));
document.write('最大值是:' + max_num);
</script>
里面判断语句部分也可以用三目运算法:
<script>
var max_num = getMaxNum(Number(prompt('请输入要比较的第一个数')), Number(prompt('请输入要比较的第二个数')), Number(prompt('请输入要比较的第三个数,可不填')));
function getMaxNum(a, b,c) {
return max_num=a>b?(a>c?a:c):(b>c?b:c);
}
document.write('最大值是:' + max_num);
</script>