javascript - 滚动超过某个点后,使用 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');
}
}
不幸的是,这对我不起作用。我没有从中得到任何错误,只是没有发生任何事情。
我想知道你们中是否有人知道如何在这方面取得成功?
任何回应将不胜感激!!
非常非常感谢,亚当
解决方案
推荐阅读
- quarkus - 如何诊断 Quarkus REST 服务 OIDC 错误(特别是 403 禁止)?
- pyqt5 - pyinstaller打包的程序运行时崩溃
- amazon-web-services - 汉莎失败!缺少 WebSocket 连接和升级标头?
- sql - TSQL 当它包含某个值时带回组
- c++ - facebook 愚蠢的 SingletonThreadLocal 令人惊讶的设计
- node.js - 获取 throw new Error(`DialogSet.add(): Invalid dialog being added.`); ^ 错误:DialogSet.add():添加的对话框无效
- python - 需要帮助将 .wav 音频文件转换为 .PNG ,然后再转换回相同的 .wav 文件
- react-native - 在 react-native 中绘制较大四边形内的四边形角
- c# - Entity Framework 6:多对多关系问题
- reactjs - 在 React 中创建带有图像的散点图