html:
@*输入框*@ <div> <input type="text" style="width: 85%; height: 34px;" onkeyup="InputChange(this)" id="txtInput"> </div> @*模拟下拉框*@ <div class="divselect" id="dpSelect"> </div>
css:
/*选择框效果*/ .divselect { float: left; position: relative; z-index: 3003; background: #fff; display: none; width: 85%; } .divselect ul { padding: 0; margin: 0; border: 1px solid #E4E4E4; background-color: #ffffff; position: absolute; z-index: 30000; margin-top: -1px; width: 100%; overflow: auto; max-height: 200px; } .divselect ul li { list-style-type: none; cursor: pointer; height: 24px; line-height: 24px; } .divselect ul li:hover { background: #ccc; }
js:
<script type="text/javascript">
//点击模拟下拉框以外的地方 下拉框消失
$(document).bind(‘click‘, function (e) {
var e = e || window.event; //浏览器兼容性
var elem = e.target || e.srcElement;
while (elem) { //循环判断至跟节点,防止点击的是div子元素
if (elem.id && elem.id == ‘dpSelect‘) {
return;
}
elem = elem.parentNode;
}
$(‘#dpSelect‘).css(‘display‘, ‘none‘); //点击的不是div或其子元素
});
//用文本框onkeyup事件触发InputChange方法 InputChange方法判断文本框文字是否改变 文字改变则触发SearchOrgName方法
var sOldValue;
sOldValue = "";
function InputChange(arg) {
var vNewValue = $(arg).val();
if (sOldValue != vNewValue) {
//根据条件查询结果并给下拉框动态赋值
SearchName(arg);
sOldValue = vNewValue;
}
}
function SearchName(arg) {
var name = $(arg).val();
//如果搜索框为空 则返回false
if (name == "") {
$("#dpSelect").attr("style", "display:none");
return false;
}
else {
$("#dpSelect").attr("style", "display:block");
}
//获取数据 并给下拉框动态赋html
$.ajax({
type: "post",
url: "......",
data: { name: name },
dataType: "",
async: false,
success: function (data) {
var strs = "";
strs += "<ul>";
for (var i = 0; i < data.length; i++) {
strs += ‘<li onclick="SetValue(this)">‘ + data[i] + ‘</li>‘;
}
strs += "</ul>";
$("#dpSelect").html(strs);
},
error: function () {
alert("查询出错");
}
});
}
//点击模拟下拉框内选项后 给文本框赋值 关闭下拉框
function SetValue(arg) {
var value = $(arg).text();
$("#txtInput").val(value);
$("#dpSelect").attr("style", "display:none");
}
</script>
原文:http://www.cnblogs.com/Alex-zqzy/p/7927891.html