Javascript:select支持手动输入功能

select下拉框的onkeydown事件,修改下拉框的值。

  function catch_keydown(sel){
   switch(event.keyCode) {
    case 13: //回车键
     event.returnValue = false;
     break;
    case 27: //Esc键
     sel.options[sel.selectedIndex].text = oldText;
     sel.options[sel.selectedIndex].value = oldValue;
     event.returnValue = false;
     break;
    case 8:  //空格健
     var s = sel.options[sel.selectedIndex].text;
     s = s.substr(0,s.length-1);
     if (sel.options[0].value==sel.options[sel.selectedIndex].text){
      sel.options[sel.selectedIndex].value=s;
      sel.options[sel.selectedIndex].text=s;
     }
     event.returnValue = false;
     break;
   }
   if (!event.returnValue && sel.onchange)
    sel.onchange(sel)
  }

select下拉框的onkeypress事件,修改下拉框的值。

  function catch_press(sel){
   if(sel.selectedIndex>=0){
    var s = sel.options[sel.selectedIndex].text + String.fromCharCode(event.keyCode);
    if (sel.options[sel.selectedIndex].value==sel.options[sel.selectedIndex].text){
     sel.options[sel.selectedIndex].value=s;
     sel.options[sel.selectedIndex].text=s;
    }
    event.returnValue = false;
    if (!event.returnValue && sel.onchange)
     sel.onchange(sel)
   }
  }

select下拉框的onfocus事件,保存下拉框原来的值。

function catch_focus(sel) {
 oldText = sel.options[sel.selectedIndex].value;
 oldValue = sel.options[sel.selectedIndex].value;
}

使用方法:

<!--调用-->
<select style='width:130px;z-index:-1' name='tmpSel'    onkeydown=catch_keydown(this) onkeypress=catch_press(this) onfocus=catch_focus(this)>
  <option value=''></option>
  <option value=''>A</option>
  <option value=''>B</option>
  <option value=''>C</option>
</select>

作者:terry,如若转载,请注明出处:https://www.web176.com/news/frontend/24303.html

(0)
打赏 支付宝 支付宝 微信 微信
terryterry
上一篇 2023年6月18日
下一篇 2023年6月23日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注