文本框/下拉菜单组合

5

我正在尝试“合并”文本框和下拉框。但它们似乎无法对齐。

enter image description here

我的代码:

<input name="" type="text" maxlength="50" style="width: 665px; padding:0px; z-index: 2; position: absolute;" />
<select name="" style="z-index: 1; width: 695px; padding:0px; position:absolute;">
    <option value="Value for Item 1" title="Title for Item 1">Item 1</option>
    <option value="Value for Item 2" title="Title for Item 2">Item 2</option>
    <option value="Value for Item 3" title="Title for Item 3">Item 3</option>
</select>

1
顺便说一下:您正在尝试创建的小部件称为组合框 - Asaph
这个fiddle看起来工作正常。编辑-我的意思是正确对齐! - Praveen Lobo
4个回答

5

我为您创建了一个演示: http://jsfiddle.net/aJaa6/

*请注意,我更改了宽度以适应面板。

CSS:

#container
{
    position: relative;
}

#input
{
position: absolute;
top: 0;
left: 0;
z-index: 999;
padding: 0;
margin: 0;
}

#select
{
position: absolute;
top: 0;
left: 0;
padding: 0;
margin: 0;
}

标记语言:

<div id="container">
<input id="input" name="" type="" style="width: 100px;">
<br>
<select id="select" name="" style="width: 115px;">
<option value="Value for Item 1" title="Title for Item 1">Item 1</option>
<option value="Value for Item 2" title="Title for Item 2">Item 2</option>
<option value="Value for Item 3" title="Title for Item 3">Item 3</option>
</select>
</div>

1

你考虑过使用FlexBox吗?它可以实现你想要的功能,并且具有许多漂亮的可定制特性。


FlexBox(至少在Firefox中)呈现得非常糟糕(至少在您链接的示例页面中)。 - kpull1
链接现在已经失效。 - cazort

1

如果您不想在绝对位置上瞎弄,这里有一种方法,当您点击文本框时,它将显示下拉菜单。 我还没有添加隐藏下拉菜单的 JavaScript,但这应该很容易实现。

 <html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
   <script>
    function showDrop(){
        $('#select').attr('size',3);
        $("#select").show();
    }
    function populateTextBox(){
            var val = $("#select option:selected").text();
        $("#input").val(val);
    }
   </script>
    </head>
<body>
   <div id="container">
<input id="input" name="" type="" style="width: 100px;" onclick="showDrop();" />
<br>
<select id="select" name="" style="display:none;width: 100px;" onclick="populateTextBox();">
<option value="Value for Item 1" title="Title for Item 1">Item 1</option>
<option value="Value for Item 2" title="Title for Item 2">Item 2</option>
<option value="Value for Item 3" title="Title for Item 3">Item 3</option>
</select>
</div>


</body>
</html>

0

你能试试这段代码吗?


#input{ position:absolute; top:2; left:2; z-index:999; padding:0; margin:0; }
#select { position:absolute; top:0; left:0; padding:0; margin:0; }
<input id="input" type="text" style="width:100px;">
<select id="selectbox" style="width:123px;">
    <option value="Value for Item 1" title="Title for Item 1">Item </option>
    <option value="Value for Item 2" title="Title for Item 2">Item </option>
    <option value="Value for Item 3" title="Title for Item 3">Item 3</option>
</select>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接