幾種實(shí)現(xiàn)動(dòng)態(tài)漸變的方法

直接進(jìn)入主題,有這樣幾種漸變方法。

一、transition過渡background-color

background-img并不支持transition方法,但是background-color可以,所以可以有漸變色彩的效果實(shí)現(xiàn)

<style>
    .box {
        max-width: 400px;
        height: 200px;
        background: olive linear-gradient(to right, rgba(0, 255, 0, 0), rgba(0, 255, 0, .5));
        transition: background-color .5s;
    }

    .box:hover {
        background-color: purple;
    }
</style>

<body>
    <div class="box"></div>
</body>
mark

二、transition過渡background

雖然background-img不支持transition,但是我們可以變相用background-position來支持transition實(shí)現(xiàn)漸變

<style>
    .box {
        max-width: 400px;
        height: 200px;
        background: linear-gradient(to right, olive, green, purple);
        background-size: 200%;
        transition: background-position .5s;
    }

    .box:hover {
        background-position: 100% 0;
    }
</style>

<body>
    <div class="box"></div>
</body>
mark

三、hover偽元素改變opacity覆蓋實(shí)現(xiàn)“漸變”

<style>
    .box {
        max-width: 400px;
        height: 200px;
        background: linear-gradient(to right, olive, green);
        position: relative;
        z-index: 0;
    }

    .box::before {
        content: '';
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        background: linear-gradient(to right, green, purple);
        opacity: 0;
        transition: opacity .5s;
        z-index: -1;
    }

    .box:hover::before {
        opacity: 1;
    }
</style>

<body>
    <div class="box"></div>
</body>
mark

實(shí)際上這里是一個(gè)顏色疊加

四、借助CSS houdini中的Properties & Values API實(shí)現(xiàn)變化效果。

<style>
    .box {
        width: 20rem;
        height: 20rem;
        background: linear-gradient(45deg,
                rgba(255, 255, 255, 1) 0%,
                var(--box__color) var(--box__gradient--position));
        transition: --box__color 0.5s ease, --box__gradient--position 1s 0.5s ease;
    }

    .box:hover {
        --box__color: #baebae;
        --box__gradient--position: 0%;
    }
</style>

<body>
    <div class="box"></div>
</body>

<script>
    if (CSS.registerProperty) {
        CSS.registerProperty({
            name: "--box__color",
            syntax: "<color>",
            initialValue: "rgba(9,9,121,1)",
            inherits: false
        });

        CSS.registerProperty({
            name: "--box__gradient--position",
            syntax: "<percentage>",
            initialValue: "60%",
            inherits: false
        });
    }

</script>
mark

更多有趣的方法歡迎大佬指出

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容