最近项目中有一个圆形轨迹转动的动画效果,
开始展示的时候我采用的是css 的transform 来写,没什么问题。
后来要求对轨迹上的元素添加事件和其他效果,jquery 中animate 没有transform的属性,所以出现了写问题,这里简单记录一下
参考文章:
css圆形轨迹:http://www.zhangyunling.com/879.html
JavaScript圆形排布:https://www.cnblogs.com/lufy/archive/2012/06/21/2558049.html
#展示
如果没有什么其他事件,只是页面转动的话,css 完全可以实现
<style>
.circle{
position: relative;
margin-top: 300px;
animation: rotate 10s linear infinite;
}
@keyframes rotate {
0% {transform:rotate(0deg);}
100% {transform:rotate(360deg);}
}
.boo {
position: absolute;
top: 50%;
left: 50%;
margin: -1em;
width: 2em;
height: 2em;
background: crimson;
}
.boo:nth-child(1) {
transform: rotate(90deg) translate(10em);
}
.boo:nth-child(2) {
transform: rotate(150deg) translate(10em);
}
.boo:nth-child(3) {
transform: rotate(210deg) translate(10em);
}
.boo:nth-child(4) {
transform: rotate(270deg) translate(10em);
}
.boo:nth-child(5) {
transform: rotate(330deg) translate(10em);
}
.boo:nth-child(6) {
transform: rotate(390deg) translate(10em);
}
</style>
<div class="circle">
<div class='boo'>1</div>
<div class='boo'>2</div>
<div class='boo'>3</div>
<div class='boo'>4</div>
<div class='boo'>5</div>
<div class='boo'>6</div>
</div>
=> 预览效果
#js 处理
参考上面文章里的js 排布我们就可以实现一些事件处理
<style type="text/css">
body,html{overflow: hidden;}
.container{position:relative;width:800px;height:800px; margin:0 auto; border:1px solid #F00;transition-duration: 2s;}
p{position:absolute;width:50px;height:50px;border: 1px #000 solid;transition-duration: 2s;text-align: center;line-height: 50px;}
</style>
<div class="container">
<p class="dot">aa</p>
<p class="box">1</p>
<p class="box">2</p>
<p class="box">3</p>
<p class="box">4</p>
<p class="box">5</p>
<p class="box">6</p>
</div>
<script type="text/javascript">
(function(gb){
var animateCircle = function(){
this.timer = null;
this.init();
}
animateCircle.prototype = {
init : function(){
this.createDom();
this.setTime();
},
createDom : function(){
//中心点横坐标
var dotLeft = ($(".container").width()-$(".dot").width())/2;
//中心点纵坐标
var dotTop = ($(".container").height()-$(".dot").height())/2;
//起始角度
var stard = 0;
//半径
var radius = 200;
//每一个BOX对应的角度;
var avd = 360/$(".box").length;
//每一个BOX对应的弧度;
var ahd = avd*Math.PI/180;
//设置圆的中心点的位置
$(".dot").css({"left":dotLeft,"top":dotTop});
$(".box").each(function(index, element){
$(this).css({"left":Math.sin((ahd*index))*radius+dotLeft,"top":Math.cos((ahd*index))*radius+dotTop});
});
},
setTime : function(){
var avd = 360/$(".box").length,
_index = 0;
this.timer = setInterval(function(){
_index ++;
var newAvd = avd * _index;
$('.container').css("transform","rotate("+newAvd+"deg)");
$('.container p').css("transform","rotate(-"+newAvd+"deg)");
},2000);
}
}
gb.animateCircle = animateCircle;
})(window)
$(function(){
var circle = new animateCircle();
$(".box").hover(function(){
var index = $(this).index();
clearInterval(circle.timer);
console.log(index);
},function(){
})
})
</script>
=> 预览效果