条形图不断增长

时间:2019-11-28 09:43:05

标签: javascript html css

我制作了带有一些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;
}

1 个答案:

答案 0 :(得分:2)

在您的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);
});