在另一个元素下面放置一个div

时间:2011-01-31 23:14:44

标签: html css

如何将div放在另一个元素下,而其余的布局不受div元素的影响?

<div style="margin:50px">
    <div style="margin:20px; padding:10px; width:100px">
        here is a little <span id="test" style="font-weight:bold">test</span>.. some text some text some text some text
    </div>
</div>
<script>
    var elm = document.getElementById('test');
    var div = elm.appendChild(document.createElement('div'));
    with(div){
        style.position = 'relative';
        style.left = elm.offsetLeft+'px';
        style.background = '#ffffff';
        style.width = '100px';
        style.height = '50px';

        innerHTML = 'wooop';
    }
</script>

2 个答案:

答案 0 :(得分:2)

使用css属性z-index或javascript样式属性zIndex。

z-index定义图层的高度。画布(通常是body标签)使用z-index 0.高于身体的任何东西,低于下面的任何东西。

css例子:

<style type="text/css">
.my_layer {
  display: block; 
  position: absolute; 
  z-index: 10; 
  top: 10px; 
  left: 10px; 
  width: 100px; 
  height: 100px;
}
</style>

javascript示例:

<script type="text/javascript">
  el = document.getElementById("my_div")
  with(el) {
    style.zIndex = 10;
    style.display = "block"; 
    style.position = "absolute"; 
    style.top = "10px"; 
    style.left = "10px"; 
    style.width = "100px"; 
    style.height = "100px";
  }
</script>

答案 1 :(得分:1)

style.left = elm.offsetLeft + "px";