相对定位和z索引

Relative positioning and z-index?

本文关键字:索引 定位 相对      更新时间:2023-09-26

以下是代码:

$(".image").hover(
function() {
    $(this).animate({ height: "100", width: "100"}, "fast");
    $("image-two").css("z-index", "-1");
}, function() {
    $(this).animate({ height: "50", width: "50"}, "fast");
    $("image").css("z-index", "0");
    }
);
$(".image-two").hover(
    function() {
        $(this).animate({ height: "100", width: "100"}, "fast");
        $("image").css("z-index", "-1");
    }, function() {
        $(this).animate({ height: "50", width: "50"}, "fast");
        $("image").css("z-index", "0");
        }
);
<div class="main">
<img src="../images/templateone.png" class="image" alt=""/>
<img src="../images/templatetwo.png" class="image-two" alt=""/>
<script src="../javascript/gallery.js"></script>
</div>
.image {
position: relative;
width: 50px;
height: 50px;   
}
.image-two {
position: relative;
width: 50px;
height: 50px;
}

这里的重点是使一个长方体在不相互移动的情况下展开。我知道z索引需要定位,但position: relative;似乎不适合我。z索引对我来说一直是一个灰色地带,我正在努力解决它。我必须使用绝对定位还是我只是做错了什么?提前谢谢。

在这种情况下,您必须使用position:absolute,并进行适当的z索引检查http://jsfiddle.net/tbHDt/1/

是的,使用绝对定位并设置图像二左侧的动画。图像的左侧默认为0,两者的顶部也默认为0。

.image {
    position: absolute;
    width: 50px;
    height: 50px;
}
.image-two {
   position: absolute;
   left: 55px;
   width: 50px;
   height: 50px;
}

$(".image-two").hover(
    function() {
        $(this).animate({ height: "100", width: "100", left:"5"}, "fast");
        $("image").css("z-index", "-1");
    }, function() {
        $(this).animate({ height: "50", width: "50", left: "55"}, "fast");
        $("image").css("z-index", "0");
        }
);