相对定位的问题在于位置是相对于它们的正常位置的,这意味着如果你在中间调整一个元素的大小,浏览器将移动并重新排列它之后的所有内容。
需要进行一些更改才能使其正常工作。如果要使用相对定位,则必须将调整大小的 div 包装在固定大小的容器中,这样在调整大小时不会破坏元素流。你的 div 有 150px 的宽度和高度,固定大小的容器必须足够大来容纳它,假设默认的盒子模型是 150px + 10px*2 padding + 1px*2border = 172px。由于元素流由容器控制,因此我将边距移动到 css 中的容器。
通过将它们包装在一个额外的固定大小的 div 中,元素流将永远不会改变,您调整大小的 div 只会流过容器的边缘,与其他容器重叠(溢出:可见)。
我还更改了您的 z-index 逻辑,因为您现在需要为容器设置 z-index(这将适用于所有子元素)。默认情况下,所有内容的 z-index 为 2。当 div 被调整回其原始状态时,我在动画结束后使用 .animate() 上的回调函数将其容器的 z-index 设置回 2。调整大小开始时,所有容器都重置为 z-index 2,以防仍有一个动画恢复到其原始状态,当前调整大小的 div 的容器设置为 z-index 3 以使其显示在所有其他容器之上。
http://jsfiddle.net/x34d3/
HTML 标记:
<div id="main" style="position:relative;z-index:1;">
<div class="container"><div id="lefttop" class="resizer">left top</div></div>
<div class="container"><div id="righttop" class="resizer">right top</div></div>
<p style="clear:both;"></p>
<div class="container"><div id="leftbottom" class="resizer">left bottom</div></div>
<div class="container"><div id="rightbottom" class="resizer">right bottom</div></div>
</div>
CSS:
.resizer { position:relative; border: 1px solid #000000; padding:10px; margin:0px; width:150px; height:150px; }
.container { position:relative; padding:0px; margin:8px; float:left; z-index: 2; width:172px; height:172px; }
javascript:
$(function(){
$(".resizer").mouseover(function() {
$(".container").css('z-index' , '2');
$(this).parent().css('z-index' , '3');
if(this.id == "lefttop"){
aoptions = {width: "340px", height: "340px", backgroundColor: "#CCCCCC", left: '0', top: '0'}
}else if(this.id == "righttop"){
aoptions = {width: "340px", height: "340px", backgroundColor: "#CCCCCC", left: '-=190', top: '0'}
}else if(this.id == "leftbottom"){
aoptions = {width: "340px", height: "340px", backgroundColor: "#CCCCCC", left: '0', top: '-=190'}
}else if(this.id == "rightbottom"){
aoptions = {width: "340px", height: "340px", backgroundColor: "#CCCCCC", left: '-=190', top: '-=190'}
}
$(this).css('z-index' , '99').animate(aoptions, 800);
}).mouseout(function(){
if(this.id == "lefttop"){
aoptions = {width: "150px", height: "150px", backgroundColor: "#FFFFFF", left: '0', top: '0'}
}else if(this.id == "righttop"){
aoptions = {width: "150px", height: "150px", backgroundColor: "#FFFFFF", left: '+=190'}
}else if(this.id == "leftbottom"){
aoptions = {width: "150px", height: "150px", backgroundColor: "#FFFFFF", left: '0', top: '+=190'}
}else if(this.id == "rightbottom"){
aoptions = {width: "150px", height: "150px", backgroundColor: "#FFFFFF", left: '+=190', top: '+=190'}
}
$(this).animate(aoptions, 800, function(){
$(this).parent().css('z-index' , '2');
});
});
});