可以手动输入值,也可以选择下拉列表值
思路:
①布局select和input,让input覆盖select,除了select的下拉图标,以方便select选择
②编写JS,为select添加onchange事件,onchange时将input的value置成select选中的值
下面给出两个实现:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GBK"/>
<title></title>
<style>
html,body {width:100%;height:100%;margin:0px;padding:0px;overflow:hidden;text-align:center;}
#container{padding:0px;position:relative;width:100px;margin:0 auto;}
#comboinput{width:70px;margin-left:0px;display:block;height:20px;font-size:15px;position:absolute;top:0px;left:0px;}//绝对定位
#comboselect{width:93px;display:block;height:26px;font-size:15px;}
</style>
</head>
<body>
<div id="container">
<input type="text" id="comboinput" style="z-index:9999;"/>
<select id="comboselect">
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
</select>
</div>
</body>
<script>
var element = document.getElementById("comboselect");
element.onchange = function ab(){ //放在后面因为id为comboselect的元素尚未加载
var index = element.options.selectedIndex;
var val = element.options[index].value;
document.getElementById("comboinput").value=val;
}
</script>
</html>
第二种实现:
<HTML>
<HEAD>
<META http-equiv='Content-Type' content='text/html; charset=GBK'>
<TITLE>可输入的下拉框</TITLE>
<style type="text/css">
.container {position:relative;margin:10px;}
.container .sel {margin-left:-100px;width:120px;}
.container .input {width:100px;height:20px;position:absolute;}
</style>
</HEAD>
<BODY>
<div class="container">
<span style="margin-left:100px;width:20px;overflow:hidden;position:absolute;">
<select class="sel" id="sel">
<option value="选项1">选项1</option> //设置value值
<option value="选项2">选项2</option>
<option value="选项3">选项3</option>
<option value="选项4">选项4</option>
</select>
</span>
<input type="text" class="input" id="input"></input>
</div>
<script type="text/javascript">
var sel = document.getElementById("sel");
var input = document.getElementById("input");
sel.onchange = function() {
input.value = sel.value;//因为option设置了value属性
}
</script>
</BODY></HTML>