点击产生红包,到指定位置
如图所示,点击按钮就产生红包,然后飞向指定位置,需要有一个斜线的角度,还需要知道点击的位置和红包的位置
html代码
<body>
<ul class="ul">
<li class=""><button onclick="hong.getBao(event,this)">点击置评</button></li>
<li class=""><button onclick="hong.getBao(event,this)">点击置评</button></li>
<li class=""><button onclick="hong.getBao(event,this)">点击置评</button></li>
<li class=""><button onclick="hong.getBao(event,this)">点击置评</button></li>
</ul>
<div class="hongbao">
<p class="text-center">88.88</p>
<p class="text-center">恭喜获得红包</p>
</div>
</body>
css代码
ul{
width: 1200px;
background-color: #ffffff;
margin: 30px auto;
padding: 20px 30px;
}
ul li{
list-style: none;
padding: 20px;
border:1px solid #ebebeb;
}
.text-center{
text-align: center;
}
.hongbao{
position: fixed;
bottom: 30px;
right: 30px;
width: 100px;
height: 100px;
background-color: red;
color: #fff;
}
.package{
position: fixed;
}
JS代码
var hong={
getBao:function(event,ob){
// alert('ces');
var package='<p class="package"><img src="images/hong.png"/></p>';
$(ob).parent().append(package);
// var win_height=$(document).height()-80; //屏幕的高度
// var win_width=$(document).width()-80; //屏幕的宽度
// console.log(event.x+','+event.y+','+win_height+','+win_width);
// $(".hongbao").position().top; //红包的高度
// $(".hongbao").position().left; //红包的宽度
// console.log($(".hongbao").position().top+','+$(".hongbao").position().left);
//
var diff_x = event.x - $(".hongbao").position().left;
var diff_y = event.y - $(".hongbao").position().top;
var data = 360*Math.atan(diff_y/diff_x)/(2*Math.PI); //获取红包飞的角度
// console.log(data);
$('.package').css({
'position':'fixed',
'left': event.x + 'px',
'top' : event.y + 'px',
'transform': "rotate("+data+"deg)"
});
$('.package').animate({
'left':$(".hongbao").position().left +'px',
'top':$(".hongbao").position().top+'px'
},9800,function(){
$(ob).parents().children('.package').remove();
});
}
}
知识点摘要
- 点击传过来this ,可以在方法里面传递参数
- 一开始使用的是屏幕的高度和宽度,然后减去固定的数值来确定红包飞向的位置,但是会在屏幕出现滚动条的时候有BUG,修改之后可以利用更加简便的,大红包位置来确定
- 对于数学函数的复习和使用
- ainimate函数的参数,最后一个参数可以在动画完成之后指定下一步动作