javascript 悬浮跟随框缓动效果

悬浮跟随框是我们在网页中经常见到的效果,我们还是使用上一实例中的运动框架去实现。

  1. 定义一个运动函数,当触发时调用,并且传递一个目标位置作为参数
  2. 运动函数内部,调用定时函数,在定时函数内部,先求出元素位置与目标位置的距离差,然后除以一个数值作为速度(由于距离差一直在缩小,所以速度值也一直在变小,从而达到缓动效果)
  3. 由于网页上位置设置最小单位是1px,所以在步骤二中的运算可能会出现小数的情况,我们需要对小数进行处理,否则元素到达的位置总是和目标位置有1px的差距。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>New Web Project</title>
		<style>
			#div1{
				width:100px;
				height:150px;
				background: red;
				border:1px solid #008000;
				right:0px;
				position: absolute;
			}
			#div2{
				width:1920px;
				height:1px;
				background:red;
				
				position: absolute;
			}
			
		</style>
		<script>
			window.οnlοad=function(){
				var oDiv=document.getElementById('div1');
				var oDiv1=document.getElementById('div2');
				var timer=null;
				oDiv.style.top=(document.documentElement.clientHeight-oDiv.offsetHeight)/2+document.documentElement.scrollTop+'px';
				window.οnscrοll=function(){
					var scrolltop=document.documentElement.scrollTop || document.body.scrollTop;
					var iTarget=(document.documentElement.clientHeight-oDiv.offsetHeight)/2+scrolltop;
					iTarget=Math.floor(iTarget);
					oDiv1.style.top=iTarget+'px';
					startMove(iTarget);
					
				};
				function startMove(itarget){
					
					clearInterval(timer);
					timer=setInterval(function(){
						var iDis=itarget-oDiv.offsetTop;
						var speed=iDis/5;
						if(iDis>=0){
							speed=Math.ceil(speed);//当speed为小于1的数时,将它变为1,从而使元素位置移动一个像素,因为小于1的像素会被近似为0
						}
						else{
							speed=Math.floor(speed);
						}
						if(oDiv.offsetTop==itarget)
						{
							clearInterval(timer);
						}
						else
						{
							oDiv.style.top=oDiv.offsetTop+speed+'px';
						}
						document.title=oDiv.offsetTop;
					},30);
					
				}
				
			};
		</script>
	</head>
	<body style="height:2000px;">
		<div id="div1">
			
		</div>
		
	</body>
</html>

运行结果图:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值