主要用到button的onmouseover, onmouseout ,onclick事件,滑鼠移到按鈕上,按鈕的透明度發生改變,移出按鈕透明度恢複。點擊按鈕,被點擊按鈕背景色改變,點擊下一按鈕該按鈕背景色改變,上一按鈕背景色恢複。效果如上圖,代碼如下。詳細介紹見代碼注釋:
將下列代碼放置於head地區:
<script language=javascript>
var preButtonID="null"; //變數用來儲存上一被點按鈕的ID,並定義初始值為null
function buttonMouseOver(buttonID){
document.getElementById(buttonID).filters.alpha.opacity=60;
//滑鼠移上時改變相應ID按鈕的透明度
}
function buttonMouseOut(buttonID){
document.getElementById(buttonID).filters.alpha.opacity=100;
//滑鼠移出時改變相應ID按鈕的透明度
}
function buttonMouseClick(buttonID){
if (preButtonID!="null"){//如果上一按鈕的ID不為初值null,則把上一按扭的背景色恢複
document.getElementById(preButtonID).style.backgroundColor="#CCCCCC";
}
document.getElementById(buttonID).style.backgroundColor="#FF0000";
//改變被點擊按鈕的背景色
preButtonID=buttonID;//把被點擊按鈕的ID賦給“上一按鈕”變數
}
</script>
<style type="text/css" >
.myInput{
filter:alpha(opacity=100); /*此句不能刪除,如果沒有,JS中無法控制按鈕的透明度*/
border:0px;
background-color:#CCCCCC;
font-family: sans-serif, Arial, Helvetica;
}
</style>
以下代碼放在body地區:
<input type=button value=BUTTON1 name=button1 id=button1 class=myInput onclick="buttonMouseClick(this.id)" onmouseover="buttonMouseOver(this.id)" onmouseout="buttonMouseOut(this.id)">
<input type=button value=BUTTON2 name=button2 id=button2 class=myInput onclick="buttonMouseClick(this.id)" onmouseover="buttonMouseOver(this.id)" onmouseout="buttonMouseOut(this.id)">
<input type=button value=BUTTON3 name=button3 id=button3 class=myInput onclick="buttonMouseClick(this.id)" onmouseover="buttonMouseOver(this.id)" onmouseout="buttonMouseOut(this.id)">
<input type=button value=BUTTON4 name=button4 id=button4 class=myInput onclick="buttonMouseClick(this.id)" onmouseover="buttonMouseOver(this.id)" onmouseout="buttonMouseOut(this.id)">
<input type=button value=BUTTON5 name=button5 id=button5 class=myInput onclick="buttonMouseClick(this.id)" onmouseover="buttonMouseOver(this.id)" onmouseout="buttonMouseOut(this.id)">
自己可以手動設定透明度和點擊後的背景顏色,是一種不錯的效果.