最近在网络中游荡的时候发现极客公园的回到顶部的 小火箭效果很棒 so~~~模仿一下
首先我们先把极客公园的回到顶部需要的图片下载到本地
嗯,就是这张图片了,看到这张图片。我想到,火箭升空的效果可以有两种方法实现,其中一种使用了css3 的keyframe关键帧技术 ,还有一种就是用js来控制background-position。
在这里我是用第二种js控制background-position来实现。至于第一种不知道的童鞋自己去搜搜吧。
首先我们先写好html代码,没什么好说的直接上代码了
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<style>
.one {width:100%;height:3000px;}
#top {background:url(./rocket_up.png) 0px 0px no-repeat;position:fixed;bottom:0px;right:10px;width:149px;height:260px;cursor: pointer;}
</style>
</head>
<body>
<div class="one"></div>
<div id="top" style="display:none;"></div>
</body>
</html>
第二部,我们想想这个效果一个可以分为几个小的效果。
1.鼠标移动滚动到页面中下部时的显示效果
2.鼠标移动到移动到div上的变色效果(这里其实不是变色二十移动了background-position)
3.火箭喷射气体的动画
4.火箭升空的效果
5.页面滚动到顶部的效果
我们一个一个来写。
第一个:
$(window).scroll(function(){
if ($(window).scrollTop()>500){
$("#top").fadeIn(500);
}
});
第二个:
$('#top').mouseenter(function() {
$(this).css('background-position', '-149px 0px');
});
$('#top').mouseleave(function() {
$(this).css('background-position', '0px 0px');
});
第三个:这里使用setInterval来达到定时改变background-position 的效果
var topPosiiton = -149;
var flyTemp = setInterval(function() {
topPosiiton += -149;
if(topPosiiton < -743) {
topPosiiton = -149;
}
$("#top").css('background-position', topPosiiton + 'px 0px');
}, 50);
第四个:
$('#top').animate({top: '-500px'} ,'normal', 'linear');
第五个:
$('html,body').animate({scrollTop: '0px'}, 800);
将以上五个效果组合起来,做一些小的调试就完成了极客公园回到顶部效果的初期模型
<!DOCTYPE HTML>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<style>
.one {width:100%;height:3000px;}
#top {background:url(./rocket_up.png) 0px 0px no-repeat;position:fixed;bottom:0px;right:10px;width:149px;height:260px;cursor: pointer;}
</style>
</head>
<body>
<div class="one"></div>
<div id="top" style="display:none;"></div>
</body>
<script>
$('#top').click(function(){
$('html,body').animate({scrollTop: '0px'}, 800);
var fly = setTimeout(function(){
$('#top').animate({top: '-500px'} ,'normal', 'linear');
var fly2 = setTimeout(function() {
$("#top").hide();
$("#top").css("top", 'auto');
$("#top").css("background-position", '0px 0px');
clearTimeout(fly2);
},1200);
clearTimeout(fly);
clearInterval(flyTemp);
}, 1000);
var topPosiiton = -149;
var flyTemp = setInterval(function() {
topPosiiton += -149;
if(topPosiiton < -743) {
topPosiiton = -149;
}
$("#top").css('background-position', topPosiiton + 'px 0px');
}, 50);
});
$('#top').mouseenter(function() {
$(this).css('background-position', '-149px 0px');
});
$('#top').mouseleave(function() {
$(this).css('background-position', '0px 0px');
});
$(window).scroll(function(){
if ($(window).scrollTop()>500){
$("#top").fadeIn(500);
}else{
//$("#top").fadeOut(1500);
}
});
</script>
</html>