javascript - 不同高度的下拉菜单 : setting height to auto breaks the rolldown

标签 javascript jquery html css

现在我有以下 fiddle :

body, * {
    margin: 0;
    padding: 0;
}
.wrapper {
    border: 1px solid black;
}

li {
  height: 100px;
}
#two {
    height: 0em;
    overflow: hidden;
    transition-property: height;
    transition: all 1s ease-in-out;
}
.wrapper:hover #two {
    height: 4em;
}

https://jsfiddle.net/ehu2cxe2/

这似乎可行,但是,在我的实际元素中,我将下拉菜单的高度设置为无论 child 有多高,他们都有不同的高度,所以这就是为什么我不能给他们一个固定的高度,比如 4em .

我试图在悬停时将其更改为 height:auto,但这会使整个事情崩溃。我做错了什么?

最佳答案

如果您知道 child 的高度,您可以使用 max-height 代替。

body, * {
    margin: 0;
    padding: 0;
}
.wrapper {
    border: 1px solid black;
}
#two {
    max-height: 0em;
    overflow: hidden;
    transition-property: height;
    transition: all 1s ease-in-out;
}
.wrapper:hover #two {
    max-height: 4em;
}
<div class="wrapper">
    <div id="one">(content)</div>
    <div id="two">
        <ul>
            <li>Menu1</li>
            <li>Menu2</li>
            <li>Menu3</li>
        </ul>
    </div>
</div>

或者使用 js/jquery,你可以获得呈现的列表高度并将其作为高度应用到 transition

var h = $('#two ul').outerHeight(),
    $two = $('#two'),
    $wrapper = $('.wrapper');

$wrapper.hover(function() {
	$two.css('height',h);
}, function() {
	$two.css('height','0');
});
body, * {
    margin: 0;
    padding: 0;
}
.wrapper {
    border: 1px solid black;
}
#two {
    height: 0em;
    overflow: hidden;
    transition-property: height;
    transition: all 1s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div id="one">(content)</div>
    <div id="two">
        <ul>
            <li>Menu1</li>
            <li>Menu2</li>
            <li>Menu3</li>
        </ul>
    </div>
</div>

您也可以使用 $.slideToggle(),但我更喜欢将动画/过渡保留在 CSS 中。

var $twoUl = $('#two ul'),
    $wrapper = $('.wrapper');

$wrapper.hover(function() {
	$twoUl.stop().slideToggle();
});
body, * {
    margin: 0;
    padding: 0;
}
.wrapper {
    border: 1px solid black;
}
#two {
    overflow: hidden;
}
#two ul {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div id="one">(content)</div>
    <div id="two">
        <ul>
            <li>Menu1</li>
            <li>Menu2</li>
            <li>Menu3</li>
        </ul>
    </div>
</div>

关于javascript - 不同高度的下拉菜单 : setting height to auto breaks the rolldown,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44863679/

相关文章:

html - 使用HTML5视频标签从Google云端硬盘流式传输视频

Javascript算术运算符不起作用

javascript - socket.io 使用 for 循环添加 socket.on 方法

javascript - 如何使用ajax从一个php页面获取数据并使用ajax将其传递到另一个php页面

jQuery Roundabout IE 图像像素化

html - Div 使表格变大而不是滚动条

javascript - 类型错误 : - is not a function

javascript - attr() 和 val() 有可用的 += 吗?

javascript - PHP/MySQL和JQuery如何交互?

javascript - 在 javascript (jQuery) 中重置变量