我想更改一个img src,同时向下滚动每20个像素,所以从顶部向下滚动100个像素,它应该更改5次,实际的src图像应该是“have 05.png”我已经做到了这一点,感谢其他教程,但在测试中,似乎不能正常工作。有人能帮我找出原因吗?
HTML
<div class="fixedContainer">
<div class="scrollableContainer">
<img class="character" id="character" src="./images/falling-01.png"/>
</div>
</div>
<div class="anotherContainer"></div>
CSS
.fixedContainer {
position: relative;
width: 100%;
height: 100%;
background-color: red;
overflow-y: scroll;
}
.scrollableContainer {
position: relative;
width: 100%;
height: 1800px;
background: rgb(34,193,195);
background: linear-gradient(0deg, rgba(34,193,195,1) 0%, rgba(253,187,45,1)
100%);
}
.anotherContainer {
position: relative;
width: 100%;
height: 800px;
background-color: white;
display: ;
}
.character {
position: fixed;
right: 140px;
top: 150px;
}
JAVASCRIPT
var image = document.getElementById("character");
var sources = ["falling-01.png", "falling-02.png", "falling-03.png", "falling-04.png", "falling-05.png", "falling-06.png", "falling-07.png", "falling-08.png", "falling-09.png"];
var i = 0;
var breakpoint = 20; // Change to whatever you like
window.addEventListener("scroll", function() {
var scrollDown = document.body.scrollTop;
if (scrollDown >= breakpoint) {
img.setAttribute(src, sources[i]);
breakpoint += 20; //Change to whatever you like
i++;
}
}
发布于 2018-12-05 08:44:22
首先,你有一个打字错误:
var image = document.getElementById("character"); <-- defined as image
img.setAttribute(src, sources[i]); <-- referenced as img
第二,查看body中的滚动位置
var scrollDown = document.body.scrollTop;
但在您的代码中,可滚动的部分不是主体
.fixedContainer {
...
overflow-y: scroll;
}
https://stackoverflow.com/questions/53623262
复制相似问题