我正在尝试通过滚动页面来创建动画,如下所示:
$(function() {
$(document).on('scroll', function() {
var top = $(document).scrollTop();
if (top > 2200 && top < 2401) {
if (top > 2200 && top < 2210) {
$('#seta2').stop().animate({left: "826px"}, 300, "easeOutQuad" );
}
if (top > 2211 && top < 2220) {
$('#seta2').stop().animate({left: "821px"}, 300, "easeOutQuad" );
}
if (top > 2221 && top < 2230) {
$('#seta2').stop().animate({left: "816px"}, 300, "easeOutQuad" );
}
if (top > 2231 && top < 2240) {
$('#seta2').stop().animate({left: "811px"}, 300, "easeOutQuad" );
}
if (top > 2241 && top < 2250) {
$('#seta2').stop().animate({left: "806px"}, 300, "easeOutQuad" );
}
if (top > 2251 && top < 2260) {
$('#seta2').stop().animate({left: "801px"}, 300, "easeOutQuad" );
}
if (top > 2261 && top < 2270) {
$('#seta2').stop().animate({left: "796px"}, 300, "easeOutQuad" );
}
if (top > 2271 && top < 2280) {
$('#seta2').stop().animate({left: "791px"}, 300, "easeOutQuad" );
}
if (top > 2281 && top < 2290) {
$('#seta2').stop().animate({left: "786px"}, 300, "easeOutQuad" );
}
if (top > 2291 && top < 2300) {
$('#seta2').stop().animate({left: "781px"}, 300, "easeOutQuad" );
}
if (top > 2301 && top < 2310) {
$('#seta2').stop().animate({left: "776px"}, 300, "easeOutQuad" );
}
if (top > 2311 && top < 2320) {
$('#seta2').stop().animate({left: "771px"}, 300, "easeOutQuad" );
}
if (top > 2321 && top < 2330) {
$('#seta2').stop().animate({left: "766px"}, 300, "easeOutQuad" );
}
if (top > 2331 && top < 2340) {
$('#seta2').stop().animate({left: "761px"}, 300, "easeOutQuad" );
}
if (top > 2341 && top < 2350) {
$('#seta2').stop().animate({left: "756px"}, 300, "easeOutQuad" );
}
if (top > 2351 && top < 2360) {
$('#seta2').stop().animate({left: "751px"}, 300, "easeOutQuad" );
}
if (top > 2361 && top < 2370) {
$('#seta2').stop().animate({left: "746px"}, 300, "easeOutQuad" );
}
if (top > 2371 && top < 2380) {
$('#seta2').stop().animate({left: "741px"}, 300, "easeOutQuad" );
}
if (top > 2381 && top < 2390) {
$('#seta2').stop().animate({left: "736px"}, 300, "easeOutQuad" );
}
if (top > 2391 && top < 2400) {
$('#seta2').stop().animate({left: "731px"}, 300, "easeOutQuad" );
}
}
else {
$('#seta2').stop().animate({left: "830px"}, 300, "easeOutQuad" );
}
});});
Run Code Online (Sandbox Code Playgroud)
但是,此代码太长,滚动高度为200px时大约需要70行,是否有更好的选择呢?
再一次,对英语不好对不起...非常感谢您的关注
您可以通过一点数学来简化整个过程。仅在范围更改时才触发动画。否则,您将在每个像素变化时停止并开始动画。另外,您当前的范围内有1px的间隙,因为您正在执行>而不是>=。
$(function() {
var prevRange = -1;
var range = -1;
$(document).on('scroll', function() {
var top = $(document).scrollTop();
if (top >= 2200 && top < 2401) {
range = Math.floor(top/10)-220;
} else {
range = -1;
}
if(range != prevRange) {
prevRange = range;
var leftPx = (826 - range*5) + "px";
$('#seta2').stop().animate({left: leftPx}, 300, "easeOutQuad" );
}
});
});
Run Code Online (Sandbox Code Playgroud)
该代码找出您所在的10px范围,然后使用该值找出要设置动画的位置,并假设您的范围均为10px范围,动画范围为每5px。
| 归档时间: |
|
| 查看次数: |
3589 次 |
| 最近记录: |