201108191816[JS] 利用 jQuery UI 美化 radio button 並加上圖示
由於工作上的需要我開始使用 jQuery 及 jQuery UI 來增進工作效率,以下用一個範例來說明如何使用 jQuery UI 的 button 功能。下面是完成之後的截圖
jQuery UI 使用相當方便,搭配 jQuery 強大的選擇器 (Selector),可以做到相當多的事情,jQuery UI 的官方網站也有許多範例和使用說明。以下網址會示範如何利用 jQuery UI 美化 radio button
jQuery UI Radio button sample code
http://jqueryui.com/demos/button/#radio
也許你跟我一樣,會覺得某些 jQuery UI 的佈景 (Themes) 讓我們搞混,現在到底選擇哪一個項目,尤其是當選項只有兩個的時候,如果可以的話,我希望能夠在已核選的地方加上小圖示來辨識,這樣就更加清楚了,然而官方網站提供的範例中只示範 button 項目如何加上圖示 (Icon),其實我們只要撰寫簡短的 jQuery 程式碼,就可以讓 radio button 也擁有小圖示。以下程式碼中讓核選項目顯示小圖示,其他項目就沒有小圖示了:
<html> <head> <link href="jquery-ui/css/theme/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css"/> <style> div { border: 2px solid #e6d0d0; margin: 10 10 10 10px; padding: 20 20 20 20px; font-size: 82%; } </style> <script src="jquery-ui/js/jquery-1.6.2.min.js"></script> <script src="jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script> <script> $(function() { var noIcon = {primary: null, secondary: null}; var withIcon = {primary: 'ui-icon-custom-tick', secondary: null}; $('input:radio').click(function(e) { // 清除所有 icon $('input[name='+e.target.name+']').button("option", "icons", noIcon).button('refresh'); if ($(e.target).button("option", "icons").primary == null) $(e.target).button("option", "icons", withIcon).button('refresh'); }); $('input:radio:checked').button({icons: withIcon}); $('div').buttonset(); }); </script> </head> <body> <div> <input type="radio" name="test1" id="r1" /> <label for="r1">選項1</label> <input type="radio" name="test1" id="r2" checked /> <label for="r2">選項2</label> <input type="radio" name="test1" id="r3" /> <label for="r3">選項3</label> <input type="radio" name="test1" id="r4" /> <label for="r4">選項4</label> <input type="radio" name="test1" id="r5" /> <label for="r5">選項5</label> </div> <div> <input type="radio" name="test2" id="u1" /> <label for="u1">選項1</label> <input type="radio" name="test2" id="u2" /> <label for="u2">選項2</label> <input type="radio" name="test2" id="u3" /> <label for="u3">選項3</label> <input type="radio" name="test2" id="u4" /> <label for="u4">選項4</label> <input type="radio" name="test2" id="u5" checked /> <label for="u5">選項5</label> </div> </body> </html>
下面連結的最後一個回覆是這支程式參考作法,連結中是使用 checkbox,將連結的範例稍加修改就可以適用於 radio button。
Jquery UI buttonset icons
http://stackoverflow.com/questions/2514650/jquery-ui-buttonset-icons
by autosun
回應