滚动图像更改

时间:2013-08-06 12:54:48

标签: javascript jquery

继续其他SO Question

此脚本更改页面滚动时的图像。但是,如果这个脚本用于具有200多个图像的视频帧,则该脚本会过大。是否可以缩短此脚本以用于大量文件?

非常感谢

1 个答案:

答案 0 :(得分:8)

次要代码调整......

的jsfiddle

http://jsfiddle.net/gvee/ygkWH/6/

HTML

<img src="http://placekitten.com/100/100" /><b>Frame: 0</b>

[说明] CSS

img, b {
    position: fixed;
    top: 0;
    left: 0;
}
body {
    height: 10000px;
}

JQuery的

// Array of images to swap between
var images = [];

// Add 200 items to array
for (i = 0; i < 200; i++) {
    images.push('http://placekitten.com/' + (100 + i) + '/' + (100 + i));
}

var totalImages = images.length;

var pageHeight = $(document).height() - $(window).height();

// Work out how often we should change image (i.e. how far we scroll between changes)
var scrollInterval = Math.floor(pageHeight / totalImages);

$(document).scroll(function () {
    // Which one should we show at this scroll point?
    i = Math.floor($(this).scrollTop() / scrollInterval);
    // Show the corresponding image from the array
    $('img').attr('src', images[i]);
    $('b').text('Frame: ' + i);
});