js實(shí)現(xiàn)下拉框具有輸入功能的方法

字號(hào):


    這篇文章主要介紹了js實(shí)現(xiàn)select下拉框具有輸入功能的方法,實(shí)例分析了兩種比較常見的實(shí)現(xiàn)方法,是非常實(shí)用的技巧,需要的朋友可以參考下
    本文實(shí)例講述了js實(shí)現(xiàn)select下拉框具有輸入功能的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:
    實(shí)現(xiàn)方法一
    代碼如下:
    <html>
    <head>
    <meta http-equiv='content-type' content='text/html; charset=gb2312'>
    <title>js實(shí)現(xiàn)可輸入的下拉框</title>
    </head>
    <body>
    <div style=position:relative;>
    <span style=margin-left:100px;width:18px;overflow:hidden;>
    <select style=width:118px;margin-left:-100px onchange=this.parentnode.nextsibling.value=this.value>
    <option value=德國>德國</option>
    <option value=挪威>挪威</option>
    <option value=瑞士> 瑞士</option>
    </select></span><input name=box style=width:100px;position:absolute;left:0px;>
    </div>
    </body>
    </html>
    實(shí)現(xiàn)方式二
    代碼如下:
    <select id=select onkeydown=select.del(this,event) onkeypress=select.write(this,event)>
    <option value=></option>
    <option value=aaa>aaa</option>
    <option value=bbb>bbb</option>
    <option value=ccc>ccc</option>
    </select>
    <input type=button value=獲取選擇值 id=test onclick=test();/>
    <script>
    var select = {
    del : function(obj,e){
    if((e.keycode||e.which||e.charcode) == 8){
    var opt = obj.options[0];
    opt.text = opt.value = opt.value.substring(0, opt.value.length>0?opt.value.length-1:0);
    }
    },
    write : function(obj,e){
    if((e.keycode||e.which||e.charcode) == 8)return ;
    var opt = obj.options[0];
    opt.selected = selected;
    opt.text = opt.value += string.fromcharcode(e.charcode||e.which||e.keycode);
    }
    }
    function test(){
    alert(document.getelementbyid(select).value);
    }
    </script><br />