首页 > 解决方案 > 通过过渡将svg渐变更改为纯白色?

问题描述

当我将它悬停时,我似乎无法在 SVG 上获得过渡。svg 里面有一个渐变......但我希望它在悬停时过渡到白色。有任何想法吗?

svg {
  width: 20px;
  height: 20px;
  path {
    transition: fill 0.4s ease;
    &:hover {
      fill: $white;
    }
  }
}
<svg id="Facebook_icon" data-name="Facebook icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="8.713" height="16.779" viewBox="0 0 8.713 16.779">
    <defs>
        <linearGradient id="linear-gradient" x1="0.5" x2="0.5" y2="1" gradientUnits="objectBoundingBox">
        <stop offset="0" stop-color="#f7d077"/>
        <stop offset="0.112" stop-color="#ffefaa"/>
        <stop offset="0.269" stop-color="#ffdb74"/>
        <stop offset="0.552" stop-color="#dba846"/>
        <stop offset="0.808" stop-color="#dba846"/>
        <stop offset="1" stop-color="#f4cd6f"/>
        </linearGradient>
    </defs>
    <path id="Icon" d="M8.713,2.785H7.134c-1.238,0-1.479.588-1.479,1.451v1.9H8.61L8.225,9.125H5.655v7.653H2.576V9.125H0V6.142H2.576v-2.2A3.594,3.594,0,0,1,6.412,0a21.049,21.049,0,0,1,2.3.117Z" fill="url(#linear-gradient)"/>
</svg>

标签: htmlcsssvg

解决方案


对于 CSSOM,渐变是 <image> 类型的,您不能从 <image> 过渡到纯色 <color>。
然而,你可以做的是从一个 <image> 过渡到另一个 <image>,所以我们应该能够在两个渐变之间进行转换,但是在撰写本文时,似乎没有浏览器支持在 svg 渐变之间进行转换,并且没有一个支持 CSS梯度作为fill值。

然而,起作用的是转换元素的stop-color值。 为了仅在鼠标悬停时发生这种情况,我确实更改了您的 svg 的结构。<stop>
<path>

svg {
  width: 20px;
  height: 20px;
}
svg stop {
  transition: stop-color 0.4s ease;
}
svg path:hover ~ defs stop {
  stop-color: white;
}
<svg id="Facebook_icon" data-name="Facebook icon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="8.713" height="16.779" viewBox="0 0 8.713 16.779">
    <path id="Icon" d="M8.713,2.785H7.134c-1.238,0-1.479.588-1.479,1.451v1.9H8.61L8.225,9.125H5.655v7.653H2.576V9.125H0V6.142H2.576v-2.2A3.594,3.594,0,0,1,6.412,0a21.049,21.049,0,0,1,2.3.117Z"
    fill="url(#linear-gradient)"/>
    <defs>
      <linearGradient id="linear-gradient" x1="0.5" x2="0.5" y2="1" gradientUnits="objectBoundingBox">
        <stop offset="0" stop-color="#f7d077"/>
        <stop offset="0.112" stop-color="#ffefaa"/>
        <stop offset="0.269" stop-color="#ffdb74"/>
        <stop offset="0.552" stop-color="#dba846"/>
        <stop offset="0.808" stop-color="#dba846"/>
        <stop offset="1" stop-color="#f4cd6f"/>
      </linearGradient>
    </defs>

</svg>


推荐阅读