这里使用Jquery UI来实现一个计算器:
<!DOCTYPE>
<html>
<head>
<title>计算器</title>
<meta charset="utf-8"/>
<script src="../jquery-ui/jquery-1.9.1.js"></script>
<script src="../jquery-ui/ui/jquery-ui.js"></script>
<link rel="stylesheet" href="../jquery-ui/themes/base/jquery-ui.css">
</head>
<body>
<style type="text/css">
span.ui-button-text-only
{
width:60px;
}
div.ui-button-text-only
{
width:230px;
text-align:right;
}
div.ui-button-text-only.ie
{
width:230px;
}
</style><div id="result">0</div><div class="touches"><span>7</span><span>8</span><span>9</span><span>/</span></div><div class="touches"><span>4</span><span>5</span><span>6</span><span>*</span></div><div class="touches"><span>3</span><span>2</span><span>1</span><span>-</span></div><div class="touches"><span>0</span><span>.</span><span>=</span><span>+</span></div> <script type="text/javascript">
var result=0;//计算结果
var previous_touche;//之前按下的键
var last_operation;//上一次运算
$("span").button().click(function(event){
var touche=$(this).text();//当前按下的键
var display=$("#result").text();//当前的显示
if(touche=="+"||touche=="-"||touche=="*"||touche=="/"||touche=="=")
{
if(previous_touche!="+"&&previous_touche!="-"&&previous_touche!="*"&&previous_touche!="/")
{
//按下+、*、/或者=:
//如果之前有运算还没有完成,则执行计算得出结果
if(last_operation=="+")
{
result+=parseFloat(display);
$("#result span").text(format_display(result));
}
else if(last_operation=="-")
{
result-=parseFloat(display);
$("#result span").text(format_display(result));
}
else if(last_operation=="*")
{
result*=parseFloat(display);
$("#result span").text(format_display(result));
}
else if(last_operation=="/")
{
result/=parseFloat(display);
$("#result span").text(format_display(result));
}
result=parseFloat($("#result").text());
}
if(touche=="=") last_operation=undefined;
else last_operation=touche;
}
else
{
//按下数字键或者小数点
//将按键值与当前的显示结果组合
//除非先前按下的按钮是运算符
if(display=="0"||previous_touche=="+"||previous_touche=="-"||previous_touche=="*"||previous_touche=="/"||previous_touche=="=")
display="";
if(display.length<16) display+=touche;
$("#result span").text(display);
}
previous_touche=touche;
});
$("div.touches").buttonset();
$("div#result").button().click(function(event){
var display=$("#result").text();
if(display=="0") result=0;
$("#result span").text("0");
});
//IE浏览器添加特殊格式
if($.browser.msie) $("div#result").addClass("ie");
//确保显示的结果不会超过16个字符
function format_display(display)
{
display+="";
if(display.length<16) return display;
if(display.match(/\./)) return display.substring(0,15);
else return ("Out of Memory");
}
</script> </body></html>
本文介绍如何使用jQueryUI库创建一个基本的计算器应用,包括HTML结构、CSS样式和JavaScript交互逻辑。
1251

被折叠的 条评论
为什么被折叠?



