模擬select下拉選單程式碼例項

antzone發表於2017-04-18

分享一段程式碼例項,它模擬實現了select下拉選單效果。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<style type="text/css">
* {
  margin: 0;
  padding: 0;
}
a {
  text-decoration: none;
  color: #666;
}
ul, ol, li {
  list-style: none;
}
.clearfix:after, .clearfix:before {
  content: "";
  display: table;
}
.clearfix:after {
  clear: both;
}
.clearfix {
  *zoom: 1;
}
.bs {
  box-sizing: border-box;
}
.input_wrap {
  width: 640px;
  padding: 20px;
  background: #f0f0f0;
  margin: 0 auto;
}
.input_wrap input {
  width: 100%;
  height: 50px;
  line-height: 50px;
  padding-left: 20px;
  border: none;
  box-shadow: 1px 1px 10px #ccc;
}
.dialog {
  width: 100%;
  background: #fff;
  margin-top: 5px;
  display: none;
}
.dialog li {
  color: #666;
  padding-left: 10px;
  box-sizing: border-box;
  height: 50px;
  line-height: 50px;
  border-bottom: 1px solid #f0f0f0;
}
</style>
</head>
<body>
<div class="input_wrap bs">
  <input type="text" readonly="readonly" placeholder="請選擇" id="input_text" class="bs" />
  <div class="dialog" id="dialog">
    <ul class="bs">
      <li>螞蟻部落一</li>
      <li>螞蟻部落二</li>
      <li>螞蟻部落三</li>
      <li>螞蟻Biu羅四</li>
    </ul>
  </div>
</div>
<script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
<script>
function Dialog(id) {
  this.id = id,
    this.Dialog_chlick();
  this.kong();
}
Dialog.prototype.Dialog_chlick = function() {
  var self = this;
  self.Dialog_input = document.getElementById(this.id);
  //console.log(Dialog_input);
  var Dialog_box = document.getElementById("dialog");
  //var flag = $(self.Dialog_input).attr("data-value");
  $(self.Dialog_input).click(function(e) {
    e.stopPropagation();
    if ($(Dialog_box).is(":hidden")) {
      $(Dialog_box).show();
    } else {
      $(Dialog_box).hide();
    }
  });
 
  $(".dialog li").click(function() {
    var this_value = $(this).text();
 
    $(Dialog_box).hide();
    self.Dialog_input.value = this_value;
  });
};
Dialog.prototype.kong = function() {
  var target = document.getElementById("dialog");
  document.onclick = function() {
 
    target.style.display = "none";
 
  };
  target.onclick = function() {
    if (document.all) {
      window.event.cancelBubble = true;
    } else {
      event.stopPropagation();
    }
  };
}
var obj = new Dialog("input_text");
</script>
</body>
</html>

相關文章