堆栈输入字段位于彼此之上

时间:2010-08-10 17:05:05

标签: javascript html css

我有两个输入字段(文本框和选择),我希望在彼此的顶部堆叠。在我的js中,我将检查某些内容的值并设置隐藏的元素样式。当我使用下面的代码时,select和textbox都是完全可见的(这是在我将其标记为隐藏之前)。是否有一个CSS属性,我可以设置,使它们直接在彼此的顶部,所以当一个隐藏时,似乎只有一个存在。谢谢你的帮助。

<div>
   <div id="agencyAccountDropDownDiv">
     <select id="AgencyAccountSelect">
     </select>
    </div>
    <div id="agencyAccountInputDiv">
     <input id="Text1" type="text" />
    </div>
</div>

4 个答案:

答案 0 :(得分:1)

您正在寻找的是堆叠技术。

1)使你的容器div相对定位: #agencyAccountDropDownDiv{position:relative;}

这样,包含div的位置完全根据其容器定位。

2)接下来给你的输入包含div的绝对位置:

#agencyAccountDropDownDiv, #agencyAccountInputDiv{position:absolute;}

以上意味着浏览器会将div堆叠起来,就像一堆卡片一样。

3)使用javascript隐藏并显示你想要的div。

var div1 = document.getElementById('agencyAccountDropDownDiv');
var div2 = document.getElementById('agencyAccountInputDiv');
div1.style.display = 'block';
div2.style.display = 'none';

或者如g.d.d.c所述,使用jquery:

$("#agencyAccountDropDownDiv").show();
$("#agencyAccountInputDiv").hide();

答案 1 :(得分:0)

这样做的方法是将第一个(背景)元素设置为绝对定位。这将阻止它占用空间,并在其上方显示以下元素。

在这种情况下,它是

#agencyAccountDropDownDiv {
    position: absolute;
}

顺便说一下,这个简单的例子你不需要div。您可以直接定位选择。

答案 2 :(得分:0)

你可以使用css将它们放在同一个地方:

#agencyAccountDropDownDiv, #agencyAccountInputDiv { position: fixed; top: 10; left: 10; }

这将相对于窗口修复它们。您将要查看其他方法的DOM Box模型和绝对与相对定位。一般来说,你可能想要的是动态显示或隐藏容器div的东西。 jQuery会让这非常简单:

$('#agencyAccountDropDownDiv').show()
$('#agencyAccountDropDownDiv').hide()

当显示或隐藏其中一个或另一个时,它将从流中移除,允许它们“占据相同的空间”。

答案 3 :(得分:0)

基本理念:

<div style="position:relative">
    <select style="width:150px" onchange="document.getElementById('aaa').value = this.options[this.selectedIndex].text">
        <option>hey hey hey hey 1</option>
        <option>hey hey hey hey 2</option>
        <option>hey hey hey hey 3</option>
    </select>
    <input id="aaa" type="text" style="position:absolute;left:0px;width:132px;border-right:0px;">
</div>

可能更好的方法

相关问题