Javascript動態改變按鈕樣式__Java

來源:互聯網
上載者:User

 

主要用到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)">
 

自己可以手動設定透明度和點擊後的背景顏色,是一種不錯的效果.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.