gpt4 book ai didi

javascript - 使用滚动更改静态定位的图像

转载 作者:太空宇宙 更新时间:2023-11-04 03:40:44 26 4
gpt4 key购买 nike

我正在尝试根据窗口的滚动位置更改静态定位图像的来源。

基本上,我想根据视口(viewport)相对于页面的位置循环浏览 MRI 扫描图像。我想浏览整个页面的所有 100 多张图片。这个长度会改变,所以我想弄清楚如何让它成比例。

我承认我是编码新手,所以最好使用伪代码而不是尝试编码:

window.image1position == ( 1 / [#images] ) * document.totalheight
window.image2position == ( 2 / [#images] ) * document.totalheight
...

if window.scrollposition == window.image1position

set image.src = image1.png

elseif window.scrollposition == window.image2position

set image.src = image2.png
...

谁能帮我解决这个问题?非常感谢任何输入。

艾伦

最佳答案

由于您没有指定 jQuery 是否可以接受,我拼凑了一些使用纯 JavaScript 快速完成此操作的方法。我没有事先为每个图像确定适当的滚动距离,而是选择在运行时引用数组索引来执行此操作。 (假设您有一个 <img id="changeImg"> 元素):

// Store image sources in array to keep track of them
var imgArray = ["img1.jpg",
"img2.jpg",
"img3.jpg"];

// Get scrollable height of body, calculate stepsize to go between images
// Partially taken from http://stackoverflow.com/questions/1145850/how-to-get-height-of-entire-document-with-javascript
var body = document.body, html = document.documentElement;
var totalHeight = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight ) - window.innerHeight;
var stepSize = totalHeight/imgArray.length;

// Bind to scroll event
window.onscroll = function(){
var scrolled = document.body.scrollTop;
var img = document.getElementById("changeImg");

// Determine correct index to use, and swap src
var imgIndex = Math.min(Math.floor(scrolled/stepSize), imgArray.length - 1);
img.src = imgArray[imgIndex];
};

这是一个 JSFiddle demonstration向您展示正在运行的代码。希望这可以帮助!如果您有任何问题,请告诉我。

关于javascript - 使用滚动更改静态定位的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24943379/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com