绝对定位的元素在离开容器边界时变得不可见

时间:2014-08-10 23:52:28

标签: javascript html css

请参阅此jsfiddle

HTML:

<div id="div1">
    <div id="div2"></div>
</div>
<div id="div3"></div>
<p>How can i make div2 appear on screen?</p>

CSS:

#div1
{
position:absolute;
    width:200px;
    height:200px;
    background-color: yellow;
    left:0px;
    top:0px;
    z-index:1;
}

#div2
{
position:absolute;    
    background-color:green;
    left:30px;
    top:30px;
    width:30px;
    height:30px;
    z-index:2;
}

#div3
{
    position:absolute;
    left:200px;
    top:0px;
    width:200px;
    height:200px;
    background-color:red;
    z-index:1;
}

JS:

var left = 0;
var div = document.getElementById("div2");
window.setInterval(function()
                   {
                  div.style.left = left + "px";
                       left = (left + 5) % 370;
                   }, 30);

问题: 当div2离开其父级边界时,div2变为不可见。如何在不更改div2的父级的情况下修复此问题。我也无法在我的应用程序中更改div的宽度和高度。

1 个答案:

答案 0 :(得分:1)

将div1上的z-index:1;更改为z-index:3; FIDDLE

#div1
{
position:absolute;
width:200px;
height:200px;
background-color: yellow;
left:0px;
top:0px;
z-index:3; // change this to a number higher than others
}