如何在滚动时缩放SVG

How to scale SVG on scroll?

本文关键字:缩放 SVG 滚动      更新时间:2023-09-26

我有一个SVG,它是一行框,我想在窗口滚动时将其缩放150%,然后恢复到原始大小。

我是JavaScript的新手,所以我不知道为什么它不起作用。

这是我的JSFiddle

以下是我的代码:

HTML:

<div class="container">
<svg class="scale" version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
 viewBox="0 0 219.7 104.3" style="enable-background:new 0 0 219.7 104.3;" xml:space="preserve">
<style type="text/css">
.st0{fill:none;stroke:#000000;stroke-width:5;stroke-miterlimit:10;}
</style>
<rect x="18.9" y="15.3" class="st0" width="22.2" height="22.2"/>
<rect x="71.5" y="15.3" class="st0" width="22.2" height="22.2"/>
<rect x="125.3" y="15.3" class="st0" width="22.2" height="22.2"/>
<rect x="177.8" y="15.3" class="st0" width="22.2" height="22.2"/>
<rect x="18.9" y="60.8" class="st0" width="22.2" height="22.2"/>
<rect x="71.5" y="60.8" class="st0" width="22.2" height="22.2"/>
<rect x="125.3" y="60.8" class="st0" width="22.2" height="22.2"/>
<rect x="177.8" y="60.8" class="st0" width="22.2" height="22.2"/>
</svg>
</div>
<div class="spacer"></div>
<div class="spacer"></div>

CSS:

.container {
  width:800px;
}
.spacer {
  height:500px;
}

JS:

  $(window).scroll(function() {
    $(".scale").css({"-moz-transform": scale(150), "webkit-transform": scale(150)});
  });

谢谢你,我真的很感激你的帮助!

我不确定,但您可能忘记了在fiddle中初始化jQuery。此外,我用引号括住了scale属性,并使用了1.5而不是150,乍一看似乎有效。

每当您像这里那样将CSS作为对象(在{花括号}中)传递时,像backgroundColor这样的属性就会变成backgroundColor,因为您需要使用类似camelBase的javascript。

这是最新的Fiddle。

 $(window).scroll(function() {
    $(".scale").css({"-moz-transform": "scale(1.5,1.5)", "webkit-transform": "scale(1.5,1.5)"});
  });

几个问题:

  • 您需要将CSS属性的值用引号括起来(否则Javascript试图将其解释为函数调用,但失败了)

  • 比例是一个比率,所以150%应该写1.5,而不是150

因此:

  $(window).scroll(function() {
    $(".scale").css({"-moz-transform": "scale(1.5)",
                     "webkit-transform": "scale(1.5)"});
  });

您可能还希望包含标准的"转换"