做網頁時常碰到這樣的場景:依使用者選擇顯示不同內容。最常見的就是登入頁——兩個表格,一個註冊、一個登入,用兩個 radio button 切換。整個過程都在同一頁完成,不跳轉、也不重整。
打開 Dreamweaver,加入兩個單選按鈕,命名為 radiobutton1 與 radiobutton2,分別給新使用者註冊與舊使用者登入使用。接著插入一個表格作為註冊區,在其中放入需要的表單元素與文字;再插入第二個表格作為登入區,同樣填入內容。介面部分到此完成。
選取第一個表格,在 HTML 檢視中修改它,為 <table> 標籤加上 id 與 style,把 display 設為 none:
<table id="newuser" style="display:none" border="0" cellspacing="0" cellpadding="0">
第二個表格用同樣方式處理,id 改為 olduser。此時按 F12 預覽,畫面上只會看到兩個單選按鈕,兩個表格都不可見。
選取 radiobutton1,為它加上 onclick 事件:
<input type="radio" name="radiobutton" value="radiobutton" onclick="newuser.style.display='';olduser.style.display='none'">
它的意思是:點 radiobutton1 時,把 newuser 的 display 設為空值(即可視),同時把 olduser 的 display 設為 none(不可視)。
radiobutton2 的 onclick 邏輯正好相反:
<input type="radio" name="radiobutton" value="radiobutton" onclick="olduser.style.display='';newuser.style.display='none'">
完成後按 F12 預覽:點 radiobutton1 顯示註冊畫面;改點 radiobutton2 時,註冊畫面隱藏、登入畫面出現。
用層也能達到相同效果,但層在網頁中的精準定位遠不如表格方便,整體版面設計也比較難維持一致。幾行簡單的程式碼換來一個實用的互動功能,值得。