1. 程式人生 > >前端開發實現(四) 按鈕選中後顏色變化

前端開發實現(四) 按鈕選中後顏色變化

今天我要實現的按鈕的動態選中,就是說在一排按鈕中選中某個按鈕,這個按鈕就會變色,其他按鈕恢復原來顏色,目的是為了讓人知道自己選中了哪個按鈕,知道自己做了什麼。

功能其實不是很難,只需要使用jQuery的功能就能實現:

分析一下思路,使用this進行判斷當前是哪個按鈕被選中了,然後用$().css改變當前按鈕的顏色,在進行修改前需要進進行一個判斷,首先把所有未被選中的按鈕的顏色改變為預設顏色,這樣做的目的是將之前選中的按鈕樣式還原。藉此起到選中哪個按鈕,哪個按鈕改變顏色的效果。

下面上程式碼:html

<div id="SupendButton-one" class="button button-primary button-small " onclick=SupendButtonClick(this);>
        <p>one</p>
    </div>
    <div id="SupendButton-two" class="button button-primary button-small "onclick=SupendButtonClick(this);>
        <p>two</p>
    </div>
    <div id="SupendButton-three" class="button button-primary button-small " onclick=SupendButtonClick(this);>
        <p>three</p>
    </div>

這裡就只上按鈕部分程式碼,其他部分不方便透露

備註:使用了ID選擇器的方法

js程式碼:

    function SupendButtonClick(obj) {
        //清空其它同類按鈕選中顏色
        $('div[id^="SupendButton-"]').css("background-color", "#4cb0f9");//按鈕原來顏色
        //點選後變色
        $(obj).css("background-color", "red");
    }