代码之家  ›  专栏  ›  技术社区  ›  Koby Douek Cicero Silva Luiz Junior

将关键帧值设置为偏移?

  •  0
  • Koby Douek Cicero Silva Luiz Junior  · 技术社区  · 6 年前

    假设我有一个 div 用指定的 height 属于 100px 我想给它制作动画,让它在 固定的 20px 高度。

    下面的代码片段展示了我如何成功地实现它。

    @keyframes foo {
        0% {
           height: 100px;
        }
        50% {
           height: 120px;
        }
        100% {
           height: 100px;
        }
    }
    
    #foo1 {
        background-color:blue;
        
        width:100px;
        height:100px;
    
        animation-name: foo;
        animation-duration: 1.4s;
        animation-iteration-count: infinite;
        animation-direction: alternate;
        animation-timing-function: ease-in-out;
    }
    <div id='foo1'>

    但是如果我需要设置 高度 属性,以便它不是 100px 它可以更改为任何其他值,但我仍然希望 高度 固定的 20PX ?

    有没有方法将animaton值设置为 抵消 原始元素值?

    2 回复  |  直到 6 年前
        1
  •  3
  •   Temani Afif    6 年前

    如果您没有任何内容并且只是一个简单的视觉动画,请增加填充:

    @keyframes foo {
        0%,100% {
           padding-bottom: 0px;
        }
        50% {
           padding-bottom: 20px;
        }
    }
    
    #foo1 {
        background-color:blue;
        
        width:100px;
        height:100px;
    
        animation-name: foo;
        animation-duration: 1.4s;
        animation-iteration-count: infinite;
        animation-direction: alternate;
        animation-timing-function: ease-in-out;
    }
    <div id='foo1'>

    或者使用CSS变量:

    @keyframes foo {
        0%,100% {
           height:var(--h,100px)
        }
        50% {
           height:calc(var(--h,100px) + 20px);
        }
    }
    
    #foo1 {
        background-color:blue;
        
        width:100px;
        height:var(--h,100px);
        display:inline-block;
        animation-name: foo;
        animation-duration: 1.4s;
        animation-iteration-count: infinite;
        animation-direction: alternate;
        animation-timing-function: ease-in-out;
    }
    <div id='foo1'></div>
    <div id='foo1' style="--h:50px;"></div>
        2
  •  1
  •   Aurel Bílý    6 年前

    我不认为有直接的方法,但你有几个解决办法:

    • 使用 padding (例如) padding-bottom )扩展元素的高度“仅当元素不应该有文本内容流入填充时才适用”
    • 使用 border _“同上
    • 使用额外的元素,例如 ::after
    • 如果已经设置了 height CSS的“外部”可能是您使用JS设置的?