1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>jq--实现自定义下拉框</title> 6 </head> 7 <style> 8 * { 9 margin: 0; 10 padding: 0 11 } 12 13 ul, 14 ol { 15 list-style: none 16 } 17 18 .select_box { 19 position: relative; 20 margin: 100px auto; 21 width: 300px; 22 } 23 24 .select { 25 padding: 0 10px; 26 line-height: 30px; 27 /* background:url("../img/icon.jpg") no-repeat right; */ 28 border: 1px solid #dedede; 29 } 30 31 .select:hover { 32 cursor: pointer; 33 } 34 35 .select span { 36 display: block; 37 } 38 39 .list { 40 display: none; 41 position: absolute; 42 top: 32px; 43 width: 298px; 44 max-height: 160px; 45 border: 1px solid #dedede; 46 border-top: none; 47 overflow-y: auto; 48 overflow-x: hidden; 49 text-overflow: ellipsis; 50 white-space: nowrap; 51 } 52 53 .list li { 54 padding: 0 10px; 55 line-height: 30px; 56 } 57 58 .list li:hover { 59 background: #F2F5F9; 60 color: #666666; 61 } 62 63 /* 滑条样式 */ 64 .list::-webkit-scrollbar { 65 width: 6px; 66 height: 6px; 67 background: transparent; 68 } 69 70 .list::-webkit-scrollbar-thumb { 71 background: transparent; 72 border-radius: 4px; 73 } 74 75 .list:hover::-webkit-scrollbar-thumb { 76 background: hsla(0, 0%, 53%, 0.4); 77 } 78 79 .list:hover::-webkit-scrollbar-track { 80 background: hsla(0, 0%, 53%, 0.1); 81 } 82 </style> 83 <body> 84 <div class="select_box"> 85 <div class="select "> 86 <span>请选择</span> 87 </div> 88 <ul class="list "> 89 <li>01</li> 90 <li>02</li> 91 <li>03</li> 92 </ul> 93 </div> 94 <div class="select_box"> 95 <div class="select "> 96 <span>请选择</span> 97 </div> 98 <ul class="list "> 99 <li>01</li> 100 <li>02</li> 101 <li>03</li> 102 <li>04</li> 103 <li>05</li> 104 <li>06060606060606060606060606060606060606060606</li> 105 </ul> 106 </div> 107 <script src="../js/jquery-1.7.2.js"></script> 108 <script> 109 $(function() { 110 $(".select").click(function() { 111 $(".list").not(this).slideUp(); 112 $(this).next(".list").slideToggle(); 113 }) 114 $(".list li").click(function() { 115 $(this).parent().prev(".select").children("span").html($(this).html()); 116 $(".list").slideUp(); 117 }) 118 $(document).bind("click", function(e) { 119 var e = e || window.event; //事件对象,兼容IE 120 var target = e.target || e.srcElement; //源对象,兼容火狐和IE 121 while (target) { 122 if (target.className && target.className == "select_box") { //循环判断至根节点,防止点击的是#selected和它的子元素 123 return; 124 } 125 target = target.parentNode; 126 } 127 $(".list").slideUp(); //点击的不是#selected和它的子元素,隐藏下拉菜单 128 }) 129 }) 130 </script> 131 </body> 132 </html>
JQ换成自己的:<script src="../js/jquery-1.7.2.js"></script>