【问题标题】:How to pass color through inline styles to animated div如何通过内联样式将颜色传递给动画 div
【发布时间】:2023-02-23 03:16:44
【问题描述】:

我有这个动画,它是反应应用程序的一部分。我需要动态传递 color(我必须通过内联样式来完成,目前它是硬编码的 black)。但是,这会破坏动画。黑色填充应该从左边开始,而不是从中间开始。事实上,它根本不是动画。如果我在 CSS 文件中留下 background: linear-gradient(to right, black 50%, transparent 0);,这将起作用。

工作示例

.container {
    position: relative;
    width: 500px;
}

.filling {
    border: 1px solid black;
    border-radius: 3px;
    width: 500px;
    height: 30px;
    display: block;
    background: linear-gradient(to right, black 50%, transparent 0);
    background-size: 200% 100%;
    background-position: right;
    animation: fill-div-with-color 8s 1s forwards;
}

@keyframes fill-div-with-color {
    100% { background-position: left;}
}
<div class="container">
    <div class="filling"/>
</div>

不工作的例子

    .container {
        position: relative;
        width: 500px;
    }

    .filling {
        border: 1px solid black;
        border-radius: 3px;
        width: 500px;
        height: 30px;
        display: block;
        background-size: 200% 100%;
        background-position: right;
        animation: fill-div-with-color 8s 1s forwards;
    }

    @keyframes fill-div-with-color {
        100% { background-position: left;}
    }
    <div class="container">
        <div class="filling" style="background: linear-gradient(to right, black 50%, transparent 0);"/>
    </div>

为什么我不能内联传递样式?

【问题讨论】:

  • a) style="linear-gradient(to...)"- 不完整,您遗漏了 background:,并且 b) 您的样式表将其应用于 .filling 元素,而您将内联样式设置为 .element
  • @CBroe b) 是一个错字。关于a),linear-gradient(...中的black是背景色?!
  • 是的,还有?这并没有改变一个事实姓名缺少要为其设置值的 CSS 属性。
  • @CBroe 现在我明白你指的是什么了。我编辑了我的问题。那是一个错字。

标签: html css reactjs


【解决方案1】:

backgroundshorthand for several background properties,包括background-sizebackground-position。由于您使用的是内联样式,.filling 中的背景样式将被覆盖。您可以通过将内联样式从 background: linear... 更改为 background-image: linear... 来解决此问题

    .container {
        position: relative;
        width: 500px;
    }

    .filling {
        border: 1px solid black;
        border-radius: 3px;
        width: 500px;
        height: 30px;
        display: block;
        background-size: 200% 100%;
        background-position: right;
        animation: fill-div-with-color 8s 1s forwards;
    }

    @keyframes fill-div-with-color {
        100% { background-position: left;}
    }
    <div class="container">
        <div class="filling" style="background-image: linear-gradient(to right, black 50%, transparent 0);"/>
    </div>

【讨论】:

    猜你喜欢
    • 2021-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    相关资源
    最近更新 更多