用jQuery建立一個可編輯的SELECT下拉控制項(HTML/CSS)__HTML

來源:互聯網
上載者:User
普通的SELECT控制項只能選擇,不能編輯,這裡可以用JS代碼來實現這個功能。基本原理是在select控制項上面添加一個input蓋住,當select改變時自動更新input的值。
<!DOCTYPE html><html lang="zh"><head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <meta name="keywords" content="">  <meta name="description" content="">  <meta name="author" content=""></head><body><style>.select-editor {    position: relative;    height: 20px;    overflow: hidden;    border: solid 1px #ccc;}.select-editor select {    position: absolute;    top: 0px;    left: 0px;    border: none;    width: 100%;    margin: 0;}.select-editor input {    position: absolute;    top: 0px;    left: 0px;    border: none;    width: 90%;}.select-editor select:focus,.select-editor input:focus {    outline:none;}.select-editor[disabled] input {    background-color: rgb(235, 235, 228);}</style>  <div class="select-editor">  <select>    <option value="OPTION 1">OPTION 1</option>    <option value="OPTION 2">OPTION 2</option>    <option value="OPTION 3">OPTION 3</option>    <option value="OPTION 4">OPTION 4</option>  </select>  <input type="text" name="host" value="" /></div><script src="/js/jquery-1.12.4.min.js"></script><script>$.fn.selectEditor = function() {  return this.each(function() {    var self      = this    var $editor   = $(self)    var $select   = $editor.find('select')    var $input    = $editor.find('input')    if ($input.size() < 1 || $select.size() < 1) {      return    }    $select.on('change', function() {      var self    = this      var option  = self.options[self.selectedIndex]      if (!option) {        return      }      $input.val(option.value)    })  })}$('.select-editor').selectEditor()</script>  </body></html>

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.