在滚动上更改图像

时间:2013-04-07 11:03:06

标签: javascript css javascript-events

在我的网站上是一张固定图片。该图像应该是“动画的”,这意味着应该迭代动画的单个帧。因此,我们的想法是拥有一个图像数组,每次用户滚动时,都会迭代数组,并且显示的图像会发生变化,从而创建动画。 我不习惯使用JS,因此我真的不知道从哪里开始。 我唯一拥有的是CSS:

#animation { 
background-repeat: no-repeat;
position : fixed; 
width: 980px;
margin: 0 auto;
}

1 个答案:

答案 0 :(得分:6)

好的,我已经为“电影/动画”中使用的固定数量的图像创建了示例。在这种情况下,数字为5.脚本将获得站点高度的图像,整个动画(5帧)将具有站点长度的长度。我已经预装并隐藏了将用于动画的图像,以确保动画能够顺利运行。

<强> HTML

<img class="hidden" src="http://coverjunction.s3.amazonaws.com/manual/low/colorful1.jpg"/>
<img class="hidden" src="http://coverjunction.s3.amazonaws.com/manual/low/colorful2.jpg"/>
<img class="hidden" src="http://coverjunction.s3.amazonaws.com/manual/low/colorful3.jpg"/>
<img class="hidden" src="http://coverjunction.s3.amazonaws.com/manual/low/colorful4.jpg"/>
<img class="hidden" src="http://coverjunction.s3.amazonaws.com/manual/low/colorful5.jpg"/>

<!-- Next image is used for first frame, before scroll -->
<img src="http://coverjunction.s3.amazonaws.com/manual/low/colorful1.jpg" id="animation" />

<div id="bottommark"></div>

<强> CSS

.hidden {
    position: absolute;
    top: -9999999px;
}

#bottommark {
    position: absolute;
    bottom: 0;
}

#animation { 
    background-repeat: no-repeat;
    position : fixed; 
    top: 0;
    width: 980px;
    margin: 0 auto;
}

body, html {
    height: 1000px; /* just for DEMO */
    margin: 0;
}

<强>的jQuery

$(document).ready(function(){
    var offset2 = $(document).height();
   var lineHF = offset2 - $("#bottommark").position().top;
    $(window).scroll(function(){
        var offset1 = $(document).height();
        var offset = $(window).scrollTop();
        var lineH = offset1 - $("#bottommark").position().top - offset;
        var lineHpart = lineHF/5; //just in case animation have 5 frames/images

        //below is code in case that animation have 5 frames.
        //If number of frames is different, edit code (add/remove if loops) 

        $("span").html(lineH);
            if (lineH > lineHpart*4) {
                $("#animation").attr("src", "http://coverjunction.s3.amazonaws.com/manual/low/colorful1.jpg");
            }
            if ((lineH < lineHpart*4) && (lineH > lineHpart*3)) {
                $("#animation").attr("src", "http://coverjunction.s3.amazonaws.com/manual/low/colorful2.jpg");
            }
            if ((lineH < lineHpart*3) && (lineH > lineHpart*2)) {
                $("#animation").attr("src", "http://coverjunction.s3.amazonaws.com/manual/low/colorful3.jpg");
            }
            if (lineH < lineHpart*2 && lineH > lineHpart*1) {
                $("#animation").attr("src", "http://coverjunction.s3.amazonaws.com/manual/low/colorful4.jpg");
            }
            if (lineH < lineHpart) {
                $("#animation").attr("src", "http://coverjunction.s3.amazonaws.com/manual/low/colorful5.jpg");
            }
        });
    });

<强> DEMO