模擬select樣式+功能,相容IE9+
阿新 • • 發佈:2019-02-07
效果:
程式碼:用了rem作單位,jquery.js
<!doctype html> <html> <meta charset="utf-8"> <title>div模擬select</title> <script> function fontAuto(){ document.documentElement.style.fontSize = document.documentElement.clientWidth/19.2 + 'px'; } fontAuto(); window.onresize=function() { fontAuto(); } </script> <style type="text/css"> html,body{ width:100%; height:100%; background:#0e3a81; } .input-select { position: relative; display: inline-block; } .input-select input { border-radius: 0; color: #00a0e9; height: 0.3rem; line-height: 0.3rem; border:1px solidrgba(96, 207, 240, 0.7); background: none; width: 1.5rem; display: block; font-size: 0.12rem; position:relative; z-index:1; text-indent:0.1rem; } .input-select .dropdown { position: absolute; top: 0.32rem; left: 0px; width: 1.52rem; padding: 0; background: rgba(18,18,30,0.79); border: none; z-index: 999; margin:0; display:none; } .input-select .dropdown li { height:0.24rem; line-height:0.24rem; font-size:0.12rem; display: block; cursor: pointer; padding-left: 0.05rem; border-top: 1px solid rgba(18,18,30,0.79); border-bottom: 1px solid rgba(18,18,30,0.79); color: #00a0e9; } .input-select .dropdown li:hover { border-top: 1px solid #00ffff; border-bottom: 1px solid #00ffff; background: rgba(18,18,30,0.6); } </style> <body> <div class="input-select"> <input type="text" data-val="全部" class="input" value="鄭爽" /> <ul class="dropdown"> <li>鄭爽-沈晨曦</li> <li>鄭爽-木子</li> <li>鄭爽-易遙</li> </ul> </div> <script type="text/javascript" src="js/jquery.min.js"></script> <script> var isBox = false; // 定義一個觸發焦點事件的開關,預設為不開啟狀態 || 也可以給input設定一個屬性,來判斷 $(".input").focus(function () { // input繫結焦點事件,觸發時開啟焦點開關 $(".dropdown").hide(); $(this).siblings(".dropdown").show(); isBox = true; }); $(".input-select").mousemove(function () { // 滑鼠進入input-box區域內開啟焦點開關 isBox = true; }); $(".input-select").mouseout(function () { // 滑鼠離開input-box區域內關閉焦點開關 isBox = false; }); $(".input").blur(function () { // input失去焦點時通過焦點開關狀態判斷滑鼠所在區域 if (isBox == true) return false; $(this).siblings(".dropdown").hide(); }); $(".dropdown").find('li').each(function () { // 傳值給input,同時關閉焦點開關 $(this).on("click", function () { isBox = false; var text = $(this).text(); $(this).parent().siblings(".input").val(text); $(this).parents(".dropdown").hide(); }) }) </script> </body> </html>