繁体   English   中英

条形图的高度不断增加

[英]Bar chart keeps growing in height

我用一些 div 制作了一个条形图。 现在我想知道当你悬停其中一个酒吧时,它的高度会增加。 我让这部分工作了,但我的问题是当我将它悬停几次时,它会继续增长并且不会回到我设置的原始高度。 我该如何解决?

css:

@keyframes grow-column {0% {transform: translateY(100%);} 100% {transform: translateY(0);}}

.chart {
    height: 500px;
    width: 100%;
    display: flex;
    flex-direction: column;
}
.bars {
    flex: 1;
    display: flex;
    flex-direction: row;
    align-items: flex-end;
    overflow: hidden;
    border-bottom: 4px solid #bab3b3;
}
.bar {
    flex: 1;
    border-bottom: none;
    margin: 0 5px;
    animation: grow-column 3s;
    background-color: red;
}


html:

<div class="chart">
    <div class="bars">
        <div class="bar" style="height:32%;"></div>
        <div class="bar" style="height:42%;"></div>
        <div class="bar" style="height:47%;"></div>
        <div class="bar" style="height:51%;"></div>
        <div class="bar" style="height:53%;"></div>
        <div class="bar" style="height:56%;"></div>
        <div class="bar" style="height:58%;"></div>
        <div class="bar" style="height:67%;"></div>
        <div class="bar" style="height:76%;"></div>
        <div class="bar" style="height:76%;"></div>
        <div class="bar" style="height:82%;"></div>
        <div class="bar" style="height:84%;"></div>
        <div class="bar" style="height:86%;"></div>
        <div class="bar" style="height:94%;"></div>
    </div>
</div>


javascript:

$(".bar").on('mouseover', function() {
    var height = calculateHeight($(this), 10);
    $(this).attr('original', $(this).height());

    $(this).animate({height: height + "px"}, 250);
}).on('mouseleave', function() {
    var height = $(this).attr('original');
    $(this).attr('original', null); // deze kan weg
    $(this).animate({height: height + "px"}, 250);
});

function calculateHeight(element, amount) {
    var parentHeight = element.parent().height();
    var height = element.height() + amount;
    return (parentHeight < height) ? parentHeight : height;
}

在您的onMouseOver事件中,您将'original'的值设置为新计算的高度 因此,在onMouseLeave您只需获取新设置的值并将其应用于元素的高度,这意味着高度不会改变。 当您再次悬停时,会采用新的(错误的)高度,并使用此错误值计算新高度。

相反,您可以使用全局变量,如下所示:

var originalHeight;
$(".bar").on('mouseover', function() {
    originalHeight = $(this).height();

    var height = calculateHeight($(this), 10);

    $(this).animate({height: height + "px"}, 250);
}).on('mouseleave', function() {

    $(this).animate({height: originalHeight + "px"}, 250);
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM