CSS缩放转换如何在不移动元素的情况下进行?

4
我想要对一个svg元素进行动画,并让它缩放(2)。这个方法可以正常工作,但问题在于我的元素有一个“x”和“y”值。因此,缩放会将元素移动到不同的位置。
但我想要在不改变位置的情况下进行缩放。'x'和'y'的值在其他地方定义,我不想在我的CSS中“硬编码”这些值。如果可能的话,我不想使用JS,应该只用纯CSS。
代码如下:
.hello {
             transition: 1s;
height: 100px;
width: 100px;
margin: 100px;
background-color: red;
transform-origin: center center;
position:relative;

        }
         .hello:hover {

transform: scale(4);
}


  <use
   id="=test"

   xlink:href="#but"
   x="100" y="20"
   width="100%"
   height="100%"
 class="hello">
  <title
     id="title31">
            I am an example toolTip
        </title>
</use>

这里可以找到一个代码示例:

https://jsfiddle.net/6agd23cL/3/


(注:该链接为英文网站,无中文页面)
1个回答

1

移除 x 和 y 属性,并增加父级 <g> 元素的 translate 属性以进行补偿。

 .hello {
     transition: 1s;
    height: 100px;
    width: 100px;
    margin: 100px;
 background-color: red;
 transform-origin: center center;
 position:relative;
   
   }
    .hello:hover {
    
 transform: scale(4);
    }
  <div id="container" style="width: 100%; height: 100%">
   <?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
  
   xmlns="http://www.w3.org/2000/svg"
 
   id="target"
   width="3600"
   height="4100"
   style="top:0;left:0;"
   version="1.1">
  <defs
     id="styles">
    <g
       id="but">
      <style
         id="style11">
                .cls-1{fill:#ffc60b;}.cls-2{stroke:#231f20;stroke-width:0.5px;}.cls-3{fill:#fff;opacity:0.1;}
            </style>
      <rect
         id="Frame"
         width="12"
         height="12"
         x="0.25"
         y="0.25"
         class="cls-1"
         rx="2"
         ry="2" />
      <circle
         id="circle14"
         cx="6.25"
         cy="6.25"
         r="4.5"
         class="cls-2" />
      <circle
         id="Highlight"
         cx="6.25"
         cy="6.25"
         r="3"
         class="cls-3" />
    </g>
  </defs>

  <g
     id="view"
     transform="translate(114.386917,29.7722462)">

     <use
       id="=test"
       
       xlink:href="#but"

       width="100%"
       height="100%"
 class="hello">
      <title
         id="title31">
                I am an example toolTip
            </title>
    </use>

  </g>
</svg>
</div>

</html>


是的,那个方法可以生效,但我的问题是在我的<g>中通常有多个"use"而不仅仅是一个。我真的很想避免在每个元素周围添加额外的<g>。我可以尝试使用变换选项来替代x和y,但是类会用比例缩放覆盖这个选项,导致元素不再处于正确的位置。 - MARL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接