我正在使用CSS设置HTML树形图样式,我试图在展开节点时使子列表向下滑动。
以下是我的简化 index.html :
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery@*" data-semver="2.1.3" src="http://code.jquery.com/jquery-2.1.3.min.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div class="node">
Div-1
<div class="children">
<div class="node">
Div-1-1
</div>
</div>
</div>
<div class="node">
Div-2
</div>
</body>
</html>
以下是 script.js :
$(document).ready(function() {
$('.node').click(function(event) {
$(event.target).toggleClass('expanded');
});
});
style.css :
.node {
border: solid 1px red;
}
.node > .children {
border: solid 1px lightblue;
overflow: hidden;
padding-left: 10px;
max-height: 0;
transition: max-height .5s ease-in;
}
.node.expanded > .children {
display: block;
max-height: 50px;
}
结果(参见。plunkr1)很好但是子列表没有滑落,它是滑动的树的其余部分,显示子列表。
所以我尝试了别的东西,我把孩子们包起来了#34; div:
<body>
<div class="node">
Div-1
<div class="childrenWrapper">
<div class="children">
<div class="node">
Div-1-1
</div>
</div>
</div>
</div>
<div class="node">
Div-2
</div>
</body>
改变了CSS:
.node {
border: solid 1px red;
}
.node > .childrenWrapper {
border: solid 1px lightblue;
overflow: hidden;
padding-left: 10px;
}
.node > .childrenWrapper > .children {
transform: translateY(-100%);
transition: transform .5s ease;
}
.node.expanded > .childrenWrapper > .children {
transform: translateY(0);
}
现在(参见。plunkr2)子列表正在滑动,但隐藏所需的overfow的包装div保持子列表的大小非常难看。
我无法找到解决此问题的方法。有什么想法吗?
答案 0 :(得分:1)
像这样更改CSS:
.node > .childrenWrapper {
transition:height .5s;
height: 0;
}
.node.expanded > .childrenWrapper {
height:auto;
}
和JS一样:
$(document).ready(function () {
$('.node').click(function (event) {
var $e = $(this),
$childrenWrapper = $e.find('.childrenWrapper'),
$children = $e.find('.children'),
h = $e.is('.expanded') ? 0 : $children.height(); // target height depending on it being expanded or not.
$childrenWrapper.height(h); // applying height to the childrenWrapper (see css transition on .node > .childrenWrapper)
$(this).toggleClass('expanded');
});
});
演示:https://jsfiddle.net/49te34wx/
顺便说一下:$(event.target).toggleClass('expanded');
可能是$(this).toggleClass('expanded');