使用jQuery动画增加DIV的高度,而不会向下推内容

3

I have this code,

HTML

<div id="header-line"></div>
<div id="main-menu"></div>
<div id="content"></div>

CSS

#header-line {
    height: 20px;
    background-color: black;
    top:0;
    left:0;
}
#main-menu {
    height: 30px;
    background-color: green;
}
#content {
    background-color: blue;
    height: 200px;
}

Javascript

$("#main-menu").hover(function () {
    $(this).stop(true, false).animate({
        height: "100px"
    });
}, function () {
    $(this).stop(true, false).animate({
        height: "30px"
    });
});

jsFiddle演示

我使用jQuery的animate函数使中间的DIV扩展其高度,但问题是它会将底部的DIV向下推。

如何使其在不推动底部DIV的情况下扩展到其上方?

6个回答

5

将HTML更改为

 <div id="header-line"></div>
 <div id="content">
     <div id="main-menu">Expands on hover</div>
 </div>

将jquery更改为

$("#main-menu").hover(function () {
    $(this).stop(true, false).animate({
        height: "100px"
    });
}, function () {
    $(this).stop(true, false).animate({
        height: "30px"
    });
});

将样式更改为

#header-line {
    height: 20px;
    background-color: black;
    top:0;
    left:0;
}
#main-menu {
    height: 30px;
    background-color: green;
    position:relative;
    z-index:3;
}
#content {
    background-color: blue;
    height: 200px;
}

主要目的是将一个div放置在另一个div内部,这样就不会把下面的div往下挤。

工作范例。


如果您想控制动画的持续时间,请在 .animate(..) 中添加另一个属性,称为 duration{duration: 100}。有关更多信息,请单击此处 - XY Li

1

这是一个CSS问题,您需要在绿色的DIV中添加position: absolute;,但您还需要解决width: Test的问题。

#main-menu {
    height: 30px;
    background-color: green;
    position: absolute;
}

1
类似这样的内容:
#header-line {
    height: 20px;
    background-color: black;
    top:0;
    left:0;
}
#parent{
    position:relative;
}
#main-menu {
    height: 30px;
    background-color: green;
    width:100%;
    position:absolute;
    top:0;
    z-index:100;
}
#content {
    background-color: blue;
    height: 200px;
    width:100%;
    position:absolute;
    /* take into account : borders, margin, previous sibling height */
    top:30px;
}

http://jsfiddle.net/techunter/7ytgy/

这是众多解决方案之一。您需要添加一个带有相对定位的父元素#parent,它将作为其子元素的参考。


1
尝试在你的 css 中添加以下内容:
#header-line {
    height: 20px;
    background-color: black;
    top:0;
    left:0;
}
#main-menu {
    height: 30px;
    background-color: green;
    z-index:1;
    position:relative;
}
#content {
    background-color: blue;
    height: 200px;
    z-index:0;
    top:50px;
    position:absolute;
    width:100%;
}

工作代码示例 http://jsfiddle.net/JuG6X/14/


1
你想要做的可以通过将这两个元素放入一个具有position:relative的包装器中来实现。
这样,您可以在父级中(新div)绝对定位子元素,即内容区域和扩展栏。
通过将它们设置为绝对位置,它们将保持在原位,扩展的div将基本上重叠在下面的内容之上:
示例在此http://jsfiddle.net/JuG6X/6/

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接