直接進(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
更多有趣的方法歡迎大佬指出