來源:急速奔跑的蝸牛 發(fā)布時間:2018-11-22 14:12:33 閱讀量:1212
效果知識點:switch關鍵字,if判斷,項目功能分析,函數(shù)封裝形參實參,字符串拼接。
文章分享之前小編推薦一下我的前端學習群:575308719,不管你是小白還是大牛,小編我都挺歡迎,不定期分享干貨,包括我精心整理的一份前端教程,歡迎初學和進階中的小伙伴。
html代碼:
<div id="jsq">
<h2>計算器</h2>
<div class="num" id="result">0</div>
<div class="but">
<ul>
<li onclick="command(7)">7</li>
<li onclick="command(8)">8</li>
<li onclick="command(9)">9</li>
<li class="tool">←</li>
<li class="tool" onclick="clearZero('j')">C</li>
<li onclick="command(4)">4</li>
<li onclick="command(5)">5</li>
<li onclick="command(6)">6</li>
<li class="tool">*</li>
<li class="tool" onclick="tools('/','g')">÷</li>
<li onclick="command(3)">3</li>
<li onclick="command(2)">2</li>
<li onclick="command(1)">1</li>
<li class="tool" onclick="tools('+','g')">+</li>
<li class="tool" onclick="tools('-','g')">-</li>
<li>0</li>
<li>00</li>
<li onclick="dian('g')">.</li>
<li class="tool">%</li>
<li class="tool2" onclick="eq('j')">=</li>
</ul>
</div>
<p>歡迎作用輕量級計算器^_^</p>
</div>
css代碼:
<style type="text/css">
*{
margin:0;/*外邊距*/
padding:0;/*內*/
}
body{
background:#000000;
}
#jsq{
width:540px;
margin:80px auto;/*上下 左右*/
box-shadow:0px 0px 10px #ffffff;
border-radius:5px;
}
#jsq h2{
color:white;
text-indent:30px;
font-weight:100;
font-size:18px;
font-family:'Microsoft Yahei';
line-height:55px;
}
#jsq .num{
border:1px solid yellow;
background:#FFF7B2;
width:480px;
margin:0 auto;
line-height:50px;
font-size:50px;
text-align:right;
border-radius:5px;
}
#jsq .but{
width:490px;
height:310px;
margin:35px auto 0px;
}
#jsq .but ul li{
color:white;
list-style-type:none;
width:80px;
height:60px;
background:#212121;
float:left;/*向左看齊*/
margin:9px;
box-shadow:0 0 5px white;
border-radius:5px;
text-align:center;
line-height:60px;
font-size:22px;
font-family:'微軟雅黑';
cursor:pointer;
}
#jsq .but ul li.tool{
background:#EF616E;
}
#jsq .but ul li.tool2{
background:#FFAF3F;
}
#jsq p{
color:white;
font-size:12px;
text-indent:30px;
line-height:50px;
}
</style>
javascript代碼:
<script type="text/javascript">
var resultDom = document.getElementById('result');
var dianmark = true; //真的
var mark = false;
function command(num){
var str = resultDom.innerText;
str = (str=="0"?"":str)
str= str+num; //字符串連接
document.title = str;
resultDom.innerText = str;
mark = true;
play(num);
}
//點擊小數(shù)點
function dian(m){
if(dianmark){
var num = resultDom.innerText;
num = num+".";
resultDom.innerText = num;
dianmark = false;
}
play(m);
}
//點擊運算符
function tools(op,m){
if(mark){
var num = resultDom.innerText;
num = (num =="0"?"":num) //如果。。。?那么就。。:否則。。
resultDom.innerText = num+op;
mark = false;
}
}
//計算等于
function eq(m){
var result = resultDom.innerText;
var r = eval(result);
resultDom.innerText = r;
mark = true;
play(m)
}
//清空
function clearZero(m){
resultDom.innerText = '0';
mark = true;
dianmark = true;
play(m)
}
function play(num){
var music = document.getElementById('music');
music.src = "wav/"+num+".wav";
music.play();
}
</script>