用滚动改变静态定位的图像
Change statically positioned image with scroll
我正在尝试根据窗口的滚动位置改变静态定位图像的来源。
基本上,我想根据视口相对于页面的位置循环遍历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演示,向您展示了实际的代码。希望这对你有帮助!如果您有任何问题,请告诉我。
相关文章:
- 如何在容器中定位旋转的图像
- 在CSS中重叠相对定位的图像
- 上传图像,重新定位,保存图像
- 如何为 ajax 生成的图像设置绝对定位
- 图像(绝对定位)相对定位容器中的水平中心
- 根据其他调整大小的html元素定位背景图像
- 在包含的html文件上定位图像
- 如何在 jQuery 中将可点击的图像定位到浏览器顶部
- 如何将背景图像定位到 html 元素的左上角和右下角
- 缩放、拖动和旋转时的图像定位
- jQuery图像滑块封面图像定位问题
- Fabric JS:使用坐标(x,y)设置图像定位
- 将图像定位在随机位置
- 是否可以将图像定位在屏幕的中心而不是浏览器的中心
- 所见即所得图像定位解决方案
- 响应式地将图像定位在背景图像上的特定目标上
- MagicZoomPlus缩放图像定位
- 是否可以使用百分比相对定位将推杆图像定位在另一个图像上?
- 将图像定位在图像上
- HTML5 Javascript图像定位