用滚动改变静态定位的图像

Change statically positioned image with scroll

本文关键字:图像 定位 静态 滚动 改变      更新时间:2023-09-26

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

基本上,我想根据视口相对于页面的位置循环遍历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演示,向您展示了实际的代码。希望这对你有帮助!如果您有任何问题,请告诉我。