首頁 >web前端 >js教程 >js實作select下拉框選單_javascript技巧

js實作select下拉框選單_javascript技巧

WBOY
WBOY原創
2016-05-16 15:27:141710瀏覽

本文實例講述了js實作select下拉框選單的詳細程式碼。分享給大家供大家參考。具體如下:
運行效果截圖如下:

具體程式碼如下:


<html>

<head>
  <title></title>
  <style type="text/css">
   #gridComboBox {
    background: #fff;
    border: 1px solid #2d78f4;
    border-radius: 2px;
    -moz-box-shadow: inset 0 0 4px #06c;
    -webkit-box-shadow: inset 0 0 4px #06c;
    box-shadow: inset 0 0 4px #06c;
  }
  </style>
</head>

<body>
  <input onclick="doClick(this,'ddd(aa/bb/cc/erererer/dfdfdfdfdfdfdfdfdfdfdfdfdf/ejjejrjerjer//erererer ////////)eee')" />
  <input onclick="doClick(this,'ddd(aa/bb/cc/erererer/dfdfdfdfdfdfdfdfdfdfdfdfdf/ejjejrjerjer//erererer ////////)eee')" style='width: 300px;' />
  <p><b>Needed Properties:</b> sender.offsetTop & sender.offsetLeft & sender.offsetHeight</p>
</body>

</html>
<script type="text/javascript">

function delGridComboBox() { // 删除弹出框
  var divContainer = document.getElementById('gridComboBox');
  if (divContainer) {
    divContainer.parentNode.removeChild(divContainer);
  }
}

function doClick(sender, str) {//str='ddd(aa/bb/cc/erererer/dfdfdfdfdfdfdfdfdfdfdfdfdf/ejjejrjerjer//erererer ////////)eee' 只取()得内容/分割做为数据源

  delGridComboBox();

  // console.log(sender);
  // for(var i in sender) 
  // {
  //   console.log(i+"|"+sender[i]);
  // }

  
  var re = /[^\)\(]*/g //取出()中的内容作为下拉数据源
  var fit = str.match(re);
  var fmt = fit[2].split('/');

  var divContainer = document.createElement('div');
  divContainer.style.width = sender.clientWidth + 2 + "px";
  divContainer.style.overflow = "hidden";
  divContainer.style.position = 'absolute'; 
  divContainer.style.top = sender.offsetTop + sender.offsetHeight + 'px';
  divContainer.style.left = sender.offsetLeft + 'px';
  divContainer.style.zIndex = 999;
  divContainer.id = "gridComboBox";

  for (var i = 0; i < fmt.length; i++) {   

    console.log('fmt[i]>>', fmt[i]);
    var txt = document.createElement('div'); 
    txt.innerHTML = fmt[i];
    txt.title = txt.innerHTML;
    txt.style.margin = 3+'px';    
    txt.addEventListener('mouseover', function changeBg(event) {
      event.target.style.fontWeight = 'bold';
      event.target.style.color = 'white';
      event.target.style.backgroundColor = '#2d78f4';
    }, false);
    txt.addEventListener('mouseout', function unChangeBg(event) {
      event.target.style.fontWeight = 'normal';
      event.target.style.color = 'black';
      event.target.style.backgroundColor = 'white';
    }, false);
    txt.onclick = function(subSender) {
      sender.value = subSender.target.innerText;
      delGridComboBox();
    };
    divContainer.appendChild(txt);
  };
  
  document.body.appendChild(divContainer);
};
</script>

以上就是js實作select下拉框選單的程式碼,希望本文所述對大家學習javascript程式設計有幫助。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn