简体   繁体   中英

How to scale SVG on scroll?

I have a SVG that is a row of boxes that I want to scale by 150% on window scroll, and then back to it's original size.

I'm fairly new to JavaScript, so I'm not sure why it isn't working.

Here is my JSFiddle

Below is my code:

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)});
  });

Thank you, I really appreciate the help!

I am not sure, but you may have forgotten to initialize jQuery within your fiddle. Additionally, I wrapped the scale property in quotes, and used 1.5 instead of 150, and it appears to work at first glance.

Whenever you are passing CSS in as an object (within the {curly brackets}) like you did here, properties like background-color become backgroundColor because you need to use the camelCase like javascript.

Here is updated Fiddle .

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

Several issues:

  • you need to enclose the values of your CSS attributes in quotes (otherwise Javascript tries to interpret it as a function call, and fails)

  • scale is a ratio, so 150% should be written 1.5, not 150

So:

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

You probably also want to include the standard "transform"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM