如何制作一個帶匹配功能的下拉框?
之前看見layui有相關組件,但是發現,如果輸入的內容在下拉框中沒有相應的匹配,就會清空當前值,搞得我很不滿意。有些代碼是從網上扒下來的,但是找不到原地址了,湊合看吧,希望有人看到提醒我一下。以下是測試解決方案:
測試代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>可搜索的下拉框</title>
<link href="https://www.layuicdn.com/layui/css/layui.css"
rel="stylesheet">
</head>
<body>
<!--[if lt IE 9]>
<script src="https://cdn.staticfile.org/html5shiv/r29/html5.min.js"></script>
<script src="https://cdn.staticfile.org/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<div class="layui-container">
<div class="layui-row">
<div class="layui-form" style="width: 100px;">
<input type="text" id="Company" class="layui-input" style="position: absolute; z-index: 2; width: 70px;"
lay-verify="required" value="111" onkeyup="search()"
autocomplete="off">
<div class="layui-input-inline">
<select id="test" class="layui-select" lay-filter="test" lay-verify="required" autocomplete="off" lay-search>
<option value="layui">layui</option>
<option value="layer">layer</option>
<option value="jquery">jquery</option>
</select>
</div>
</div>
</div>
</div>
< script type="text/javascript" src="http://libs.baidu.com/jquery/1.11.1/jquery.min.js"></script>
< script type="text/javascript" src="./layui/layui.js"></script>
< script type="text/javascript">
document.onmouseup = function(e){
var e = e || window.event;
var target = e.target || e.srcElement;
var _con = $('#test').next().find("div")
if(!_con.is(target) && _con.has(target).length === 0){
$("#test").next().find("dl").css({
"display" : "none"
});
}else{
$("#test").next().find("dl").css({
"display" : "block"
});
}
}
layui.use(['form'], function() {
$=layui.jquery;
layui.form.on('select(test)', function(data) {
$("#Company").val(data.value);
$("#test").next().find("dl").css({
"display" : "none"
});
layui.form.render();
});
window.search = function() {
var value = $("#Company").val();
$=layui.jquery;
$("#test").val(value);
layui.form.render();
$("#test").next().find("dl").css({
"display" : "block"
});
var dl = $("#test").next().find("dl").children();
var j = -1;
for (var i = 0; i < dl.length; i++) {
if (dl[i].innerHTML.indexOf(value) <= -1) {
dl[i].style.display = "none";
j++;
}
if (j == dl.length - 1) {
$("#test").next().find("dl").css({
"display" : "none"
});
}
}
}
});
</script>
</body>
</html>
以上為全部代碼
另外要注意的是,此處用到的layui與IE8不兼容,具體體現在當下拉框取值為空的時候,IE8會報錯,因此需要修改layui的源碼,一共需要修改三處:
一、
d=t(p[0].options[i]).html()
需要修改成
d=t(p[0].options[p[0].selectedIndex == -1 ? 0 : p[0].selectedIndex]).html()
二、
d=t(p[0].options[a]).html()
修改為
d=t(p[0].options[p[0].selectedIndex == -1 ? 0 : p[0].selectedIndex]).html()
三、
f=t(l.options[l.selectedIndex])
修改為
f=t(l.options[l.selectedIndex == -1 ? 0 : l.selectedIndex])
以上錯誤均為同一類錯誤,另外我用的是layui-v2.5.4(目前的最新版本)來測試的,至於jquery的引用自己看。以下我用四類瀏覽器進行測試,發現都可行,其中由於win10沒有IE8,IE8的環境是在IE11的瀏覽器中設置了仿真。