首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >更改img源,每20个像素

更改img源,每20个像素
EN

Stack Overflow用户
提问于 2018-12-05 08:06:01
回答 1查看 48关注 0票数 0

我想更改一个img src,同时向下滚动每20个像素,所以从顶部向下滚动100个像素,它应该更改5次,实际的src图像应该是“have 05.png”我已经做到了这一点,感谢其他教程,但在测试中,似乎不能正常工作。有人能帮我找出原因吗?

HTML

代码语言:javascript
复制
<div class="fixedContainer">
        <div class="scrollableContainer">
            <img class="character" id="character" src="./images/falling-01.png"/>
        </div>
</div>

<div class="anotherContainer"></div>

CSS

代码语言:javascript
复制
.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

代码语言: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++;
}
}
EN

回答 1

Stack Overflow用户

发布于 2018-12-05 08:44:22

首先,你有一个打字错误:

代码语言:javascript
复制
var image = document.getElementById("character"); <-- defined as image
img.setAttribute(src, sources[i]); <-- referenced as img

第二,查看body中的滚动位置

代码语言:javascript
复制
var scrollDown = document.body.scrollTop;

但在您的代码中,可滚动的部分不是主体

代码语言:javascript
复制
.fixedContainer {
  ...
  overflow-y: scroll;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53623262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档