【问题标题】:How to change position of svg on hover with a transition delay如何在具有过渡延迟的悬停时更改 svg 的位置
【发布时间】:2019-06-06 14:28:00
【问题描述】:

我正在尝试在悬停时将导航栏中的 svg 图标移动到左侧,我可以这样做,但我需要元素通过类似 transition : all .5s; 的东西顺利移动 问题是 svg 标签不接受 css 中的过渡属性,所以我尝试在容器上使用过渡,但这不起作用,它只是立即移动而没有过渡效果。

HTML

  <div id="sidenav-icon-section">
            <li>
                <a href="/">
                    <img src="/assets/images/home.svg" alt="home" onload="SVGInject(this)">
                </a>
          </li>
   </div>

我使用 SVGInject 库在浏览器中转换我的 svg 代码,结果如下:

 <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" width="64px" height="64px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve" data-inject-url="http://localhost:4200/assets/images/home.svg" _ngcontent-c1="">

<polygon fill="none" stroke="#000000" stroke-width="2" stroke-miterlimit="10" points="32,3 2,33 11,33 11,63 23,63 23,47 39,47   39,63 51,63 51,33 62,33 "></polygon></svg>

我还有另一个 svg 图标,它有一个 path 标签而不是 polygon

CSS

  #sidenav-icon-section {
    top: 25%;
    position: relative;

    li {
      position: relative;
      transition: all .5s;

      &:hover svg {
        left: 7%;
      }
    }
  }

我尝试将过渡到和“左”属性应用到路径和多边形元素,但此时没有任何反应,它们甚至没有移动。

【问题讨论】:

    标签: html css svg sass


    【解决方案1】:

    您正试图在位置为static 的元素上设置属性left。请尝试使用负边距。此外,您将过渡应用到错误的元素。


    svg { transition: margin-left .5s }
    
    li:hover svg {
     margin-left: -7px;
    }
    <ul id="sidenav-icon-section">
      <li class="item">
        <a href="/">
          <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Layer_1" x="0px" y="0px" width="64px" height="64px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xml:space="preserve" data-inject-url="http://localhost:4200/assets/images/home.svg"
            _ngcontent-c1="">
    
    <polygon fill="none" stroke="#000000" stroke-width="2" stroke-miterlimit="10" points="32,3 2,33 11,33 11,63 23,63 23,47 39,47   39,63 51,63 51,33 62,33 "></polygon></svg>
        </a>
      </li>
    </ul>

    scss 等价物:

    li {
      svg { transition: margin-left .5s; }
      &:hover svg {
        margin-left: -7px;
      }
    }
    

    【讨论】:

    • @naspy971 我刚刚重读了您的描述并了解到您无法在 svg 元素上应用过渡。这是有原因的吗?
    • 我昨天在尝试将此属性应用于 svg 标签时遇到了问题,但我仍然无法让您的代码在我的情况下工作,真的不知道为什么,元素仍然会立即移动。 ... :(
    • 如果您可以在 sn-p、codepen 或其他任何工具中复制您的问题。我们或许可以为您提供帮助
    • 谢谢,我通过使用 transform: translateX(7%);而不是 left 或 marging/padding 属性
    猜你喜欢
    • 2014-03-17
    • 2021-08-28
    • 2012-03-12
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-22
    相关资源
    最近更新 更多