我想在向下滚动每20个像素的同时更改img src,所以从顶部向下100像素应该更改了5次,实际的src图像应为“ falling-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++;
}
}
答案 0 :(得分:4)
首先您有错别字:
tr -d '\r' < Input_file > temp_file && mv temp_file Input_file
第二,您正在查看滚动位置的主体
var image = document.getElementById("character"); <-- defined as image
img.setAttribute(src, sources[i]); <-- referenced as img
但是在您的代码中,可滚动部分不是主体
var scrollDown = document.body.scrollTop;
答案 1 :(得分:1)
您的语法有一些问题:
img
和image
src
而非'src'
display: ;
中的{li> .anotherContainer
如果您使用window.pageYOffset
代替document.body.scrollTop
,则应该可以使用。
您可以使用
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset :
(document.documentElement || document.body.parentNode ||
document.body).scrollTop;