html 中可以自定義輸入的 select 下拉列表
阿新 • • 發佈:2019-01-11
在專案開發中,往往有這種需求:那就是需要下拉選擇已有的資料列表,當沒有自己需要的資料時,往往需要去管理這些列表資料的畫面去新增,或者在下拉列表後面放一個快捷按鈕,先新增,然後再選。
那麼問題就來了,如果按照上面的操作,往往需要很多步驟,能不能當沒有可選專案時,直接在下拉列表上輸入呢?
答案是可以的。下面就是用 JS 實現了下拉列表上自定義選項的功能,請參考。
<!DOCTYPE html> <html> <head> <title>可編輯的下拉列表</title> </head> <style type="text/css"> .cls_select_span { position:absolute; border:1pt solid #c1c1c1; overflow:hidden; width:188px; height:19px; clip:rect(-1px 190px 190px 170px); } .cls_input_span { position:absolute; border-top:1pt solid #c1c1c1; border-left:1pt solid #c1c1c1; border-bottom:1pt solid #c1c1c1; width:170px; height:19px; } .cls_option_defined { color:#c2c2c2; } .cls_select { width:190px; height:20px; margin:-2px; } .cls_input { width:170px; height:15px; border:0pt; } </style> <body> <span class="cls_select_span"> <select id="id_select" class="cls_select" onChange="selectOnChangeFunc()"> <option value="" class="cls_option_defined">---自定義---</option> <option value="開發部">開發部</option> <option value="市場部">市場部</option> <option value="銷售部">銷售部</option> </select> </span> <span class="cls_input_span"> <input type="text" id="id_input" class="cls_input" value="可選擇也可自定義輸入"> </span> <script> function selectOnChangeFunc() { document.getElementById('id_input').value = document.getElementById('id_select').options[document.getElementById('id_select').selectedIndex].value; } </script> </body> </html>