首页 > 解决方案 > 滚动超过某个点后,使用 vanilla Javascript 更改 SVG 文件中 Id 的颜色

问题描述

正如标题所说,我的 HTML 中有一个对象,即 SVG

      <object data="images/parallax_2/buildings_1.2.svg" type="image/svg+xml" id="building_1">

该 SVG 是我在 illustrator 中制作的建筑物。当我向下滚动页面时,我希望该建筑物的某些窗户可以改变颜色,就好像里面有人在打开灯一样。

在 SVG 文件中,这些是我要更改的窗口:

    <g>
    <polygon id="WINDOW_x5F_1" class="st107" points="583.3,1114.5 583.4,1047.9 607.4,1052 607.3,1118.7      "/>
    <polygon class="st107" points="628.1,1122.3 628.2,1055.7 652.2,1059.8 652.1,1126.5      "/>
    <polygon class="st107" points="672.9,1130.1 673,1063.4 697,1067.6 696.9,1134.2      "/>
    <polygon class="st107" points="717.6,1137.8 717.7,1071.1 741.8,1075.3 741.6,1142        "/>
    <polygon class="st107" points="762.4,1145.6 762.5,1078.9 786.5,1083.1 786.4,1149.7      "/>
    <polygon class="st107" points="807.2,1153.4 807.3,1086.7 831.3,1090.9 831.2,1157.5      "/>
    <polygon class="st107" points="851.9,1161.1 852.1,1094.5 876.1,1098.7 876,1165.3        "/>
    <polygon class="st107" points="896.7,1168.9 896.8,1102.2 920.9,1106.4 920.7,1173.1      "/>
    <polygon class="st107" points="941.5,1176.6 941.6,1110 965.6,1114.2 965.5,1180.8        "/>
</g>

如您所见,我更改了其中一个的 ID,因此我可以在 index.html 页面上使用我的 Javascript 定位它:

    window.onscroll = function changeClass(){

  var scrollPosY = window.pageYOffset | document.body.scrollTop;

  // Get the Object by ID
  var a = document.getElementById("building_1");

  // Get the SVG document inside the Object tag
  var svgDoc = a.contentDocument;

  // Get one of the SVG items by ID;
  var svgItem = svgDoc.getElementsByClassName('st107');

  // Set the class to something else
  if(scrollPosY > 100) {
      svgItem.className = ('st1071');
} else if(scrollPosY <= 100) {
     svgItem.className =  ('st1071');
}
}

不幸的是,这对我不起作用。我没有从中得到任何错误,只是没有发生任何事情。

我想知道你们中是否有人知道如何在这方面取得成功?

任何回应将不胜感激!!

非常非常感谢,亚当

标签: javascriptsvg

解决方案


推荐阅读